- Preparing Your Machine to Work with Strings
- Working with Strings
- Initializing Strings
- Comparing Strings
- Concatenating Strings
- Finding the String Length
- Comparing and Concatenating Strings in the Sample Application
- Creating Strings from Characters
- Using Escape Characters
- Using Literal Strings
- Accessing the String's Characters
- Finding a Substring within a String
- Extracting Part of the String
- Splitting a String
- Joining a String
- Uppercasing and Lowercasing
- Formatting Strings
- Finishing the Sample Application
- Representing Objects as Strings
- Allocating Strings with StringBuilder
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(@"\"); where index is a variable that will store the zero-based position of the character within the string, str is the variable you want to search, and @"\" is the string you are searching for.
Type int index=str.LastIndexOf(@"\"); to search for the last occurrence of a substring within the string (Figure 4.44).
Figure 4.44 The IndexOf and LastIndexOf functions let you search for a character in the string.
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 .exe in a string containing "MyProgram.exe." The IndexOf function returns the index of the first character in the substring, in this case nine.