#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
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: