#101 – Use Contains() to Discover If A String Contains Other Strings

You can use String.IndexOf to search for a substring within another stringIndexOf returns a 0-based index of the string that you’re searching for.

But if you don’t care about the location of the substring and just want to know whether it’s contained in the larger string, you can use the String.Contains method.  You can also search for individual characters.  Note that the search is case sensitive.

 string s = "A man, a plan, a canal";
 bool b = s.Contains("canal");   // true
 b = s.Contains("Canal");        // false (case-sensitive)
 b = s.Contains('p');            // true

You can also search for a particular substring at the start or the end of a string.

string s = "Call me Ishmael";
 bool b = s.StartsWith("me");       // false
 b = s.EndsWith("Ishmael");         // true
 b = s.StartsWith("Call");          // true
Advertisements