C# Language String Manipulation Finding a string within a string

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Using 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


Got any C# Language Question?