开发者

how would you remove the blank entry from array

开发者 https://www.devze.com 2023-02-06 13:14 出处:网络
How would you remove the blank item from 开发者_JAVA技巧the array? Iterate and assign non-blank items to new array?

How would you remove the blank item from 开发者_JAVA技巧the array?

Iterate and assign non-blank items to new array?

String test = "John, Jane";

//Without using the test.Replace(" ", "");

String[] toList = test.Split(',', ' ', ';');


Use the overload of string.Split that takes a StringSplitOptions:

String[] toList = test.Split(new []{',', ' ', ';'}, StringSplitOptions.RemoveEmptyEntries);


You would use the overload of string.Split which allows the suppression of empty items:

String test = "John, Jane";
String[] toList = test.Split(new char[] { ',', ' ', ';' }, 
                             StringSplitOptions.RemoveEmptyEntries);

Or even better, you wouldn't create a new array each time:

 private static readonly char[] Delimiters = { ',', ' ', ';' };
 // Alternatively, if you find it more readable...
 // private static readonly char[] Delimiters = ", ;".ToCharArray();

 ...

 String[] toList = test.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries);

Split doesn't modify the list, so that should be fine.


string[] result = toList.Where(c => c != ' ').ToArray();


Try this out using a little LINQ:

var n = Array.FindAll(test, str => str.Trim() != string.Empty);


You can put them in a list then call the toArray method of the list, or with LINQ you could probably just select the non blank and do toArray.


If the separator is followed by a space, you can just include it in the separator:

String[] toList = test.Split(
  new string[] { ", ", "; " },
  StringSplitOptions.None
);

If the separator also occurs without the trailing space, you can include those too:

String[] toList = test.Split(
  new string[] { ", ", "; ", ",", ";" },
  StringSplitOptions.None
);

Note: If the string contains truely empty items, they will be preserved. I.e. "Dirk, , Arthur" will not give the same result as "Dirk, Arthur".


string[] toList = test.Split(',', ' ', ';').Where(v => !string.IsNullOrEmpty(v.Trim())).ToArray();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号