I have a string such as the following:
string a = "foo,,,,,,,bar, baz, qux";
Usually a.Split(",")
would be okay to split a string by the comma, but with the above situation it would result in many empty strings due to the commas.
Is there a simple way to split a string by one or many occurrences of the separator, so that the result would be something like ["foo","bar","baz","qux"]
?
You can simply use StringSplitOptions
to remove the empty results.
In .NET Core, you can pass a single character to string.Split
and use StringSplitOptions
var output = a.Split(',', StringSplitOptions.RemoveEmptyEntries);
In .NET Framework, you have to pass the single char in a char array (char[]
) like so:
var output = a.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
EDIT:
Thanks to @Innat3 and @Fildor for pointing out differences in Core and Framework.
use StringSplitOptions.RemoveEmptyEntries
:
var parts = a.Split(new [] {',',' '}, StringSplitOptions.RemoveEmptyEntries)
The unfortunate part in some versions of .NET is that you have to pass an array of delimiters with this method rather than a single delimiter, but the output is what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With