36

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?

1
  • You should edit your question to remove null and only state empty strings. string.Split doesn't give null strings, just empty ones. Commented Mar 11, 2009 at 19:06

5 Answers 5

112

Try this:

yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
Sign up to request clarification or add additional context in comments.

3 Comments

That does not compile. You need to use new char[]{';'} as the first parameter.
One thing to note is that this will not remove strings consisting of only whitespace.
Not works as expected. ex: var a = "1" + "," + "" + "," + "2" + "," + " " + "," + "3" + "," + " " + "," + null + ","+"4"; . a.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); . Console.WriteLine(a.ToString()); will give result of 1,,2, ,3, ,,4
2

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));

3 Comments

You could possibly insert a .Select(s => s.Trim()) between Split and Where so that whitespace-only strings will get removed as well.
Note: The Split method never produces null values.
@TamasCzinege you can use string.IsNullOrWhiteSpaces instead of trim()
2
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;
}

Comments

0

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

Comments

0
                words = poly[a].Split(charseparators, StringSplitOptions.RemoveEmptyEntries);

                foreach (string word in words)
                    {   
                        richTextBox1.Text += (d + 1)+ "  " + word.Trim(',')+ "\r\n";
                        d++;
                    }

charseparators is a space

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.