zohair
zohair

Reputation: 2369

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

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?

Upvotes: 36

Views: 46447

Answers (5)

bjoiuzt
bjoiuzt

Reputation: 11

                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

Upvotes: 0

Sameer Shaikh
Sameer Shaikh

Reputation: 21

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

Upvotes: 2

Blessed Geek
Blessed Geek

Reputation: 21684

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

Upvotes: 0

sgriffinusa
sgriffinusa

Reputation: 4221

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

Upvotes: 2

Tamas Czinege
Tamas Czinege

Reputation: 121444

Try this:

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

Upvotes: 112

Related Questions