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

2020-02-08 06:50发布

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?

5条回答
唯我独甜
2楼-- · 2020-02-08 07:18

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, "([;][;]+)", ";");
查看更多
一纸荒年 Trace。
3楼-- · 2020-02-08 07:36

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));
查看更多
冷血范
4楼-- · 2020-02-08 07:36
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;
}
查看更多
爷的心禁止访问
5楼-- · 2020-02-08 07:41
                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

查看更多
倾城 Initia
6楼-- · 2020-02-08 07:42

Try this:

yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
查看更多
登录 后发表回答