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

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

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: