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

前端 未结 5 1496
自闭症患者
自闭症患者 2020-12-14 06:40

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

相关标签:
5条回答
  • 2020-12-14 07:17

    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));
    
    0 讨论(0)
  • 2020-12-14 07:23

    Try this:

    yourString.Split(new string[] {";"}, StringSplitOptions.RemoveEmptyEntries);
    
    0 讨论(0)
  • 2020-12-14 07:23
    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;
    }
    
    0 讨论(0)
  • 2020-12-14 07:25

    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, "([;][;]+)", ";");
    
    0 讨论(0)
  • 2020-12-14 07:31
                    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

    0 讨论(0)
提交回复
热议问题