Splitting A String Into An Array In C# & .NET
[C#, .NET]
A common task you will carry out is, given a string, to convert it into an array delimited by a chosen token.
For example:
This is a string that we want to split
If we want to delimit it using a space, we would use the Split method of the string, like this,
var input = "This is a string that we want to split";
var splitArray = input.Split(" ");
foreach (var entry in splitArray)
{
Console.WriteLine($"'{entry}'");
}
If we run this code, it will print the following:
'This'
'is'
'a'
'string'
'that'
'we'
'want'
'to'
'split'
This seems simple enough.
Complications arise when there is more than one token in succession.
For example:
This is a string that we want to split
Here, we can see there are multiple spaces following some of the words.
The same code will print the following:
'This'
'is'
'a'
''
''
''
'string'
'that'
''
''
'we'
'want'
'to'
''
''
'split'
You can see here that the array contains multiple elements with empty strings.
Usually, you don’t want this to happen.
Luckily, the Split method supports this natively - you pass it the StringSplitOptions.RemoveEmptyEntries enum, like this:
splitArray = input.Split(" ", StringSplitOptions.RemoveEmptyEntries);
foreach (var entry in splitArray)
{
Console.WriteLine($"'{entry}'");
}
This will now print the following:
'This'
'is'
'a'
'string'
'that'
'we'
'want'
'to'
'split'
The enum instructs the Split operation to remove all elements consisting only of empty strings.
TLDR
The StringSplitOptions.RemoveEmptyEntries enum when passed to String.Split removes all empty strings from the returned array.
The code is in my GitHub.
Happy hacking!