#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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

  1. Splendor says:

    I’m teaching myself C# for a new job and just wanted to say thanks for putting all of these together. I’ve found them very useful.

  2. Peter Chamberlin says:

    Typo: “use IndexOf so search” → ‘use IndexOf to search’

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: