- Jun 6, 2003
- 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
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); where segment is a variable to store the substring, str is the original string, index1 is the zero-based starting position of the substring that you want to extract, and len is the number of characters you wish to extract (Figure 4.46).
Figure 4.46 The Substring function 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.
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 - 1 to get the number of characters.
One other variation of the Substring function lets you type string segment = str.Substring(index1); without specifying the length for the substring. This variation assumes the substring will be all the characters starting at index1 (Figure 4.47).
Figure 4.47 If you specify only a starting index, Substring gives you a string from the index until the end of the original string.