Getting rid of null/empty string values in a C# array

45,209

Solution 1

Try this:

yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);

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

Solution 3

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:
45,209
zohair
Author by

zohair

Updated on July 08, 2020

Comments

  • zohair
    zohair almost 4 years

    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?

  • Tamas Czinege
    Tamas Czinege about 15 years
    You could possibly insert a .Select(s => s.Trim()) between Split and Where so that whitespace-only strings will get removed as well.
  • Guffa
    Guffa about 15 years
    That does not compile. You need to use new char[]{';'} as the first parameter.
  • Guffa
    Guffa about 15 years
    Note: The Split method never produces null values.
  • denver
    denver over 10 years
    One thing to note is that this will not remove strings consisting of only whitespace.
  • PSR
    PSR over 7 years
    @TamasCzinege you can use string.IsNullOrWhiteSpaces instead of trim()
  • PSR
    PSR over 7 years
    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