Better way to check a list of characters?

There has to be a better way than doing this
myWord == "-" || myWord == "~" || myWord == "—"...
myWord == "-" || myWord == "~" || myWord == "—"...
I also don't really want to make a array and have to loop through them all because that seems like code would pile up quickly. I'm hoping for a function that does what I'm looking for?
6 Replies
Angius
Angius3mo ago
new[]{"a", "b", "c", "d"}.Contains(myWord)
new[]{"a", "b", "c", "d"}.Contains(myWord)
Or you could make an extension method or something, say
public static class StringExtensions
{
public static bool IsAnyOf(this string needle, params string[] haystack)
{
return haystack.Contains(needle);
}
}
public static class StringExtensions
{
public static bool IsAnyOf(this string needle, params string[] haystack)
{
return haystack.Contains(needle);
}
}
used with
myWord.IsAnyOf("a", "b", "c", "d")
myWord.IsAnyOf("a", "b", "c", "d")
333fred
333fred3mo ago
myWord is "-" or "~" or ...
Angius
Angius3mo ago
Duh, of course, how could I forget about pattern matching...
LPeter1997
LPeter19973mo ago
If all single letter, "-~—…”.Contains(letter)
TizzyT
TizzyT3mo ago
If you are trying see if a string contains any of the characters you specify then:
string charList = "-~—"; // the 3 chars from your example
myWord.Any(c => charList.contains(c));
string charList = "-~—"; // the 3 chars from your example
myWord.Any(c => charList.contains(c));
jcotton42
jcotton423mo ago
Note this only works with constants, unfortunately.
Want results from more Discord servers?
Add your server