Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty strings from c# array?

Tags:

c#

I am removing values with less than 8 characters from an array, but empty strings still remain. How to get rid of them?

for (int i = 0; i < reportbOR.Length; i++)
{
    border = "border:" +reportbOR[i].colorborder;
    string[] text_arr = border.Split('\n');

    foreach (var item in text_arr)
    {
        if (item.Length < 8)
            border = border.Replace(item, "");
    }
}
like image 912
JOHN SMITH Avatar asked Feb 27 '26 14:02

JOHN SMITH


1 Answers

You can use the overload of string.Split which accepts a StringSplitOptions enum:

string[] text_arr = border.Split(new string[] { "\n" },
  StringSplitOptions.RemoveEmptyEntries);

Since it's unclear as to when you are having issues removing the empty entries, and you are also replacing strings with 8 or less characters with empty strings, you can use Linq:

text_arr = text_arr.Where(a => !string.IsNullOrWhitespace(a)).ToArray();

You can read about the overload here: stringsplitoptions

And here: string.split

EDIT Here it is in one line:

string[] text_arr = border.Split(new string[] { "\n" }, 
                    StringSplitOptions.RemoveEmptyEntries)
                    .Where(a => !string.IsNullOrWhitespace(a) && a.Length >= 8)
                    .ToArray();
like image 79
Ryan Wilson Avatar answered Mar 01 '26 04:03

Ryan Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!