In C# you can easily check if a string contains one character or a series of characters using the .Contains()
method on the String
object. Below is a list of examples on how Contains
can be used:
var myString = "abcdef";
var containsAString = myString.Contains("a"); //true
var containsBcdString = myString.Contains("bcd"); //true
var containsAcdString = myString.Contains("acd"); //false
var containsAbcString = myString.Contains("ABC"); //false
var containsAbcStringIgnoreCase = myString.Contains("ABC", StringComparison.InvariantCultureIgnoreCase); //true
In the above we define a string called myString
and then call Contains
with different strings to see if there is a match. From this we can see that Contains
can match one character or a series of characters and that it is case sensitive per default. By providing ´StringComparison.InvariantCultureIgnoreCase` as a second parameter the case can be ignored.
If you need the index of the beginning of the string instead, then you can use IndexOf
. It takes the exact same parameters, here are some examples:
var myString = "abcdef";
var indexOfAString = myString.IndexOf("a"); //0
var indexOfBcdString = myString.IndexOf("bcd"); //1
var indexOfAcdString = myString.IndexOf("acd"); //-1
var indexOfAbcString = myString.IndexOf("ABC"); //-1
var indexOfAbcStringIgnoreCase = myString.IndexOf("ABC", StringComparison.InvariantCultureIgnoreCase); //0
IndexOf
returns -1 if the string to match is not found, else it will return the index of it starting from 0, as it is zero based.
That is all
I hope you enjoyed this short post on how to check if a character is in a string using Contains
or IndexOf
. Please feel free to leave a comment down below, I read all of them :)