Finding a string within a string
suggest changeUsing the System.String.Contains
you can find out if a particular string exists within a string. The method returns a boolean, true if the string exists else false.
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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents