views:

1239

answers:

3

I have a program where an array gets its data using string.Split(char[] delimiter). (using ';' as delimiter.)

Some of the values, though, are null. I.e. the string has parts where there is no data so it does something like this:

1 ;2 ; ; 3;

This leads to my array having null values.

How do I get rid of them?

+17  A: 

Try this:

yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
DrJokepu
Beat me by a few seconds :(
Joel Coehoorn
That does not compile. You need to use new char[]{';'} as the first parameter.
Guffa
Guffa: Thanks, I totally forgot about that.
DrJokepu
+1  A: 

You could use the Where linq extension method to only return the non-null or empty values.

string someString = "1;2;;3;";

IEnumerable<string> myResults = someString.Split(';').Where<string>(s => !string.IsNullOrEmpty(s));
sgriffinusa
You could possibly insert a .Select(s => s.Trim()) between Split and Where so that whitespace-only strings will get removed as well.
DrJokepu
Note: The Split method never produces null values.
Guffa
A: 

You should replace multiple adjacent semicolons with one semicolon before splitting the data.

This would replace two semicolons with one semicolon:

datastr = datastr.replace(";;",";");

But, if you have more than two semicolons together, regex would be better.

datastr = Regex.Replace(datastr, "([;][;]+)", ";");
Blessed Geek