Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string by one or many occurrences of a single character

Tags:

c#

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"]?

like image 666
lp-pixel Avatar asked Jan 26 '23 13:01

lp-pixel


2 Answers

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.

like image 130
dvo Avatar answered Jan 28 '23 14:01

dvo


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.

like image 22
D Stanley Avatar answered Jan 28 '23 15:01

D Stanley