Splitting Strings

If you want to split a string into multiples strings, you can use the Split method. Let’s take a look at the different overloads of the Splitmethod. The Split method returns a string array that contains the substrings inside each of its elements. The first one accepts an array of character which are the delimiters that will determine where to split each substring.

string message = "The quick brown fox jumps over the lazy dog.";
string[] substrings = message.Split(' ');

foreach (string s in substrings)
{
    Console.WriteLine(s);
}
The
quick
brown
fox
jumps
over
the
lazy
dog.

We used the ‘ ‘ character to separate each word in the sentence since each word is separated by spaces. The words were stored in the substrings array. We then printed each word in separate lines by using a foreach statement.

You can limit the number of substrings to return by using another overload of Split.

string message = "The quick brown fox jumps over the lazy dog.";
string[] substrings = message.Split(" ".ToCharArray(), 3); 

foreach (string s in substrings)
{
    Console.WriteLine(s);
}
The
quick
brown fox jumps over the lazy dog.

The second argument determines the maximum number of substrings. The output shows that it properly separated the first two words, and the remaining of the string was stored in the final element of the array.

Another overload uses the enumeration StringSplitOptions. This enumeration contains 2 values, None and RemoveEmptyEntries. By passing StringSplitOptions.None, you can have an empty substring in the result array. Using StringSplitOptions.RemoveEmptyEntries removes substrings that are empty. This is demonstrated by the following codes.

string message = "string1#string2##string4#string5";
string[] results = message.Split("#".ToCharArray(), StringSplitOptions.None);

foreach (string s in results)
{
    Console.WriteLine(s);
}
string1
string2

string4
string5

The overloaded Split method accepts a character array as the first argument that’s why we used the ToCharArray() method. We used the “#” as the delimiter for the substrings.The second argument is the StringSplitOption value. We passed None, so even if the substring is empty, as demonstrated by the third substring, it will still be included in the results. Let’s try using the RemoveEmptyEntriesvalue.

string message = "string1#string2##string4#string5";
string[] results = message.Split("#".ToCharArray(),
                                 StringSplitOptions.RemoveEmptyEntries);

foreach (string s in results)
{
    Console.WriteLine(s);
}
string1
string2
string44string5

As you can see, the final results didn’t include the empty third substring.

This technique is often used when storing data in a text file. Often, data in stored in a text file separates each field by using a delimiter such as “#”. .NET can extract the string in a text file, store it in a string and then use the Split method to process the each of the data.