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.
     string filename = @"c:\documents and settings\picard\my documents\captainslog1.txt"; int driveMark = filename.IndexOf(@"\"); string drive = filename.Substring(0,driveMark); int baseDirMark = filename.IndexOf(@"\",  driveMark+1  ); string baseDir = filename.Substring(driveMark+1,                 baseDirMark - driveMark) int captNameMark = filename.IndexOf(@"\",  baseDirMark+1  ); 

graphics/tick.gif 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 - 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.
     string filename = @"c:\documents and settings\picard\mydocuments\captainslog1.txt"; int extMark = filename.IndexOf(".");  string ext = filename.Substring(extMark+1);  



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net