HomeComputer programmingC#: Split String Using a Variable Length Delimiter

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" }

RELATED ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android