#100 – Using IndexOf to Search for Characters Within A String

You can search for the following within a string:

  • A single character
  • One of a set of characters
  • A substring

You search for a single character in a string using the String.IndexOf method, which returns a 0-based index into the string.

 string s = "Thomas Paine";
 int n = s.IndexOf('a');     // 4 (1st 'a')

You can also specify a starting position for the search.  So we can find the next occurrence of ‘a’ this way:

 n = s.IndexOf('a', n+1);    // 8 (start search after 1st 'a')

You can search for the first occurrence of one of a set of characters using the IndexOfAny method.

 string s = "Thomas Paine";
 char[] vowels = new char[] {'a','e','i','o','u'};
 int n = s.IndexOfAny(vowels);     // 2
 n = s.IndexOfAny(vowels, n + 1);  // 4

You can also use IndexOf to search for substrings within a string.

 string s = "A man, a plan, a canal";
 int n = s.IndexOf("an");       // 3
 n = s.IndexOf("an", n + 1);    // 11
Advertisement