Manipulating Strings in C#—Extracting Part of the String
Extracting Part of the String
If you read the section titled "Finding a Substring within a String" you know that developers often want to find the index of a certain character within the string, then place a portion of the string up to that character into a separate variable. Suppose you have a path to a string like "C:\Dir1\SubDir2\SubDir3\MyFile.txt." What if you wanted to extract the filename minus its extension and put that into a separate variable? First you would find the index of the last occurrence of the backslash character, then you could find the index of the ".txt" segment. Once you had those two indices, you could tell the system to give you the characters that are within them.
To extract part of a string based on indices:
- Using a string variable type
string segment = str.Substring(index1,len);wheresegmentis a variable to store the substring,stris the original string,index1is the zero-based starting position of the substring that you want to extract, andlenis the number of characters you wish to extract (Figure 4.46).
- Using a string variable type

- Figure 4.46. The
Substringfunction can be used to extract a segment of the string. You simply specify the starting index and the number of characters and the function builds another string from that portion of the original string.
Tips
- In the example code you see that sometimes to get the number of characters you wish to extract you obtain the index for the character before the first character of the substring, then the index for the character after the end of the substring, and then you use the formula:
lastindex - firstindex - 1to get the number of characters.
- In the example code you see that sometimes to get the number of characters you wish to extract you obtain the index for the character before the first character of the substring, then the index for the character after the end of the substring, and then you use the formula:
- One other variation of the
Substringfunction lets you typestring segment = str.Substring(index1);without specifying the length for the substring. This variation assumes the substring will be all the characters starting atindex1(Figure 4.47).
- One other variation of the

- Figure 4.47. If you specify only a starting index,
Substringgives you a string from the index until the end of the original string.
|

