Manipulating Strings in C#—Finding a Substring within a String
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
Finding a Substring within a String
The topic of finding a character within a string and the following topic "Extracting Part of the String" normally go hand in hand. Often in string manipulations a developer will search for the first occurrence or the last occurrence of a character and extract the piece either before the character or after the character. For example, let's say you have a string that contains the path to a file, such as C:\Windows\System\regsvr32.exe. What if you wanted to place the path to the file and the filename itself into two different string variables? One way to do that is to find the last instance of the backslash character, then extract the characters before the backslash and put those characters in a variable, and then put the characters after the backslash into another variable.
To find the first or last occurrence of a character within the string:
- Using a string variable type
int index = str.IndexOf(@"\");whereindexis a variable that will store the zero-based position of the character within the string,stris the variable you want to search, and@"\"is the string you are searching for.
- Using a string variable type
- or
- Type
int index=str.LastIndexOf(@"\");to search for the last occurrence of a substring within the string (Figure 4.44).
- Type
Tips
- You can search for a single character or for a substring. Here's how to search for a substring. Let's say you were searching for
.exein a string containing"MyProgram.exe."TheIndexOffunction returns the index of the first character in the substring, in this case nine.
- You can search for a single character or for a substring. Here's how to search for a substring. Let's say you were searching for
|


