Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# split string and remove empty string

Tags:

c#

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

like image 616
Sahil Sharma Avatar asked Sep 28 '17 10:09

Sahil Sharma


3 Answers

var mobileNos = number.Replace(" ", "")
.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
like image 157
Andreas Zita Avatar answered Sep 20 '22 18:09

Andreas Zita


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.

like image 38
arslanaybars Avatar answered Sep 20 '22 18:09

arslanaybars


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);
like image 21
Ali Avatar answered Sep 18 '22 18:09

Ali