#106 – Using String.Split to Parse A String into Substrings

If you have a longer string consisting of substrings separated by a common delimiter, you can break the string into substrings using the Split method.

 string names = "John,Mary,Elvis,Ringo";
 string[] nameList = names.Split(new char[] {','});

 Console.WriteLine(nameList[0]);    // John
 Console.WriteLine(nameList[1]);    // Mary
 Console.WriteLine(nameList[2]);    // Elvis
 Console.WriteLine(nameList[3]);    // Ringo

Notice that because Split takes an array of characters, you can specify more than one character to use as the delimiter.

You can also split based on delimiters that are strings, rather than single characters.  (We also have to add a parameter indicating whether we want the function to return empty strings).

 string names = "John - Mary - Elvis - Ringo";

 // Same result as before - we get four names, without spaces or dash
 string[] nameList = names.Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);

#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