Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development

  • Print
  • + Share This
This chapter is from the book

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.44Figure 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.

  • + Share This
  • 🔖 Save To Your Account