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.

    or

  • 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.
     string filename = @"c:\documents and settings\"; filename += "picard\my documents\"; filename += "captainslog1.txt"; int driveMark = filename.  IndexOf(  @"\"); int fileMark = filename.  LastIndexOf  (@"\"); 

graphics/tick.gif 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 .exe in a string containing "MyProgram.exe." The IndexOf function returns the index of the first character in the substring, in this case nine.




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