c# split string and remove empty string

Viewed 51834

I want to remove empty and null string in the split operation:

 string number = "9811456789,   ";
 List<string> mobileNos = number.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(mobile => mobile.Trim()).ToList();

I tried this but this is not removing the empty space entry

5 Answers
var mobileNos = number.Replace(" ", "")
.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();

As I understand it can help to you;

string number = "9811456789, ";
List<string> mobileNos = number.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToList();

the result only one element in list as [0] = "9811456789".

Hope it helps to you.

a string extension can do this in neat way as below the extension :

        public static IEnumerable<string> SplitAndTrim(this string value, params char[] separators)
        {
            Ensure.Argument.NotNull(value, "source");
            return value.Trim().Split(separators, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim());
        }

then you can use it with any string as below

 char[] separator = { ' ', '-' };
 var mobileNos = number.SplitAndTrim(separator);

I know it's an old question, but the following works just fine:

string number = "9811456789,   ";
List<string> mobileNos = number.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();

No need for extension methods or whatsoever.

"string,,,,string2".Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

return ["string"],["string2"]

Related