C#: Split String Using a Variable Length Delimiter

C# string types have a method to split themselves when a certain delimiter is encountered. This method returns a string array that contains the substrings that are delimited by elements of a specified Unicode character array.

Splitting Strings Using char[]

Breaking up a sentence string into its individual words with a space delimiter is a common requirement. Doing this though a call to the String.Split() method would look something like this:

string words = "This is a list of words, with: a bit of punctuation.";
string [] split = words.Split(new Char [] {' ', ',', '.', ':'});

This would produce the string array:

{ "This", "is", "a", "list", "of", "words", "with", "a", "bit", "of", "punctuation" }

Dividing a string using spaces with the method works like a charm! However, what if we wanted to split using a more complex delimiter?

Splitting Strings Using string[]

For our next example, let us make our delimiter more complex by dividing only on occurrences of comma and space and occurrences of multiple letters such as “ae”?

We can use another String.Split() methods for this as well. This example demonstrate the String.Split(String[], StringSplitOptions) method. StringSplitOptions determines if the .Split() method will return array elements that include an empty string.

Here is our example code:

string words = "This is a list of words: aesthetics, praefect";
string[] separators = {", ", "ae"};
string[] split = words.Split(separators, StringSplitOptions.None);

This would produce the string array:

{ "This is a list of words: ", "sthetics", "pr", "fect" }


About Aaron St. Clair

Aaron St. Clair is a tech guru studying Computer Science at Appalachian State University in Boone, North Carolina. When he's not tinkering with new gadgets, modding systems, or slaving away at the mercy of the Tech-Recipe overlords, you can find him exploring the high country.
View more articles by Aaron St. Clair

The Conversation

Follow the reactions below and share your own thoughts.

Leave a Reply