Check if string contains a character in C#
StackOverflow user Samantha J T Star asked if there is a string method in C# to check if a string contains a specific character, upper or lower case. They would like to do something like this:
if (def.SomeFunction("s")) { }
There are multiple ways of doing this in C#. One is the Contains
extension method from the System.Linq
namespace:
using System.Linq;
...
if (def.ToLower().Contains('s')) { }
Another way is to use one of the Contains
overloads of the string
class:
// Check by passing a char:
if (def.ToLower().Contains('s')) { }
// Check by passing a string:
if (def.Contains("s", StringComparison.CurrentCultureIgnoreCase) != -1) { }
Create your own extension methods
It is also possible to write your own extension methods for easier reuse:
public static class MyStringExtensions
{
public static bool ContainsAnyCaseInvariant(this string haystack, char needle)
{
return haystack.IndexOf(needle, StringComparison.InvariantCultureIgnoreCase) != -1;
}
public static bool ContainsAnyCase(this string haystack, char needle)
{
return haystack.IndexOf(needle, StringComparison.CurrentCultureIgnoreCase) != -1;
}
}
Then calling them would look like this:
if (def.ContainsAnyCase('s')) { }
// Or:
if (def.ContainsAnyCaseInvariant('s')) { }
In most cases, when dealing with user data, you probably want to use CurrentCultureIgnoreCase
instead of InvariantCultureIgnoreCase
, because that way you let the system handle upper/lowercase issues, which depend on the language. When dealing with computational issues, like names of HTML tags and so on, you want to use the invariant culture.
For example: In Turkish, the uppercase letter I
in lowercase is actually ı
without a dot, and not i
with a dot.