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

2020-02-08 07:04发布

问题:

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:

Try this:

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


回答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:

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


回答4:

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


回答5:

                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