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

风格不统一 提交于 2019-12-17 22:56:41

问题


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



来源:https://stackoverflow.com/questions/635751/getting-rid-of-null-empty-string-values-in-a-c-sharp-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!