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?

share|improve this question
You should edit your question to remove null and only state empty strings. string.Split doesn't give null strings, just empty ones. – Samuel Mar 11 '09 at 19:06

4 Answers

up vote 45 down vote accepted

Try this:

yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
share|improve this answer
Beat me by a few seconds :( – Joel Coehoorn Mar 11 '09 at 18:25
3  
That does not compile. You need to use new char[]{';'} as the first parameter. – Guffa Mar 11 '09 at 18:44
Guffa: Thanks, I totally forgot about that. – DrJokepu Mar 11 '09 at 18:49

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));
share|improve this answer
You could possibly insert a .Select(s => s.Trim()) between Split and Where so that whitespace-only strings will get removed as well. – DrJokepu Mar 11 '09 at 18:29
1  
Note: The Split method never produces null values. – Guffa Mar 11 '09 at 18:45
public static string[] nullLessArray(string[] src)
{
    Array.Sort(src);
    Array.Reverse(src);
    int index = Array.IndexOf(src, null);

    string[] outputArray = new string[index];

    for (int counter = 0; counter < index; counter++)
    {
       outputArray[counter] = src[counter];
    }

    return outputArray;
}
share|improve this answer

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, "([;][;]+)", ";");
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.