#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);
Advertisements