String can be split into collection of substrings based on a defined character (separator) using Split() function. Split is part of String class which exists in the System namespace.
Split function is overloaded and has various forms which allow to:
- pass separator as a single character, array of characters, single string or array of strings;
- define maximum number of substrings in output array;
- define split options like removing empty elements from returned collection.
Below you can find examples which present each of above options. Every case has variable named input containing string to be split, variable named output which is array of strings being a result of Split function. Achieved substrings are printed to the console with following code:
1 |
foreach (var item in output) { Console.WriteLine(item); } |
Split by a single character
1 2 |
string input = "Hello world!"; var output = input.Split(' '); |
Result:
1 2 |
Hello world! |
Split by array of characters
1 2 |
string input = "A!B?C!D?E"; var output = input.Split(new char[] { '!', '?' }); |
Result:
1 2 3 4 5 |
A B C D E |
Split by a single string
1 2 |
string input = "One, two, three"; var output = input.Split(", "); |
Result:
1 2 3 |
One two three |
Split by array of strings
There is no form of Split which accepts only one input parameter which would be array of strings. As a result of what we need to pass second parameter which is split options. In below example we use “None”, which behaves the same as previous three examples where we didn’t pass such parameter.
1 2 |
string input = "One, two, three. Four, five, six"; var output = input.Split(new string[] { ", ", ". " }, StringSplitOptions.None); |
Result:
1 2 3 4 5 6 |
One two three Four five six |
Split with maximum number of substrings
In below example we limit the number of substrings in the output collection to three. It can be easily done by passing integer parameter on the second place to Split function.
1 2 |
string input = "One, two, three, four, five, six"; var output = input.Split(", ", 3); |
Result:
1 2 3 |
One two three, four, five, six |
Split with option to remove empty items from the output
1 2 |
string input = "One,,two,three,four,,five"; var output = input.Split(",", StringSplitOptions.RemoveEmptyEntries); |
Result:
1 2 3 4 5 |
One two three four five |
Without StringSplitOptions.RemoveEmptyEntries or with StringSplitOptions.None the output would look like:
1 2 3 4 5 6 7 |
One two three four five |