Finding a string within a string

suggest change

System.String.Contains reports whether a string contains a particular substring. It returns true when the substring occurs and false otherwise. Contains(string) uses an ordinal comparison. The string overloads of IndexOf and LastIndexOf use the current culture, so the same characters can produce a different result.

string s = "Hello World";
bool stringExists = s.Contains("ello");  //stringExists =true as the string contains the substring

Using the System.String.IndexOf method, you can locate the starting position of a substring within an existing string.

Note the returned position is zero-based, a value of -1 is returned if the substring is not found.

string s = "Hello World";
int location = s.IndexOf("ello"); // location = 1

To find the first location from the end of a string, use the System.String.LastIndexOf method:

string s = "Hello World";
int location = s.LastIndexOf("l"); // location = 9

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents