如何从阵列中删除空白条目?如何从阵列中删除空白条目
迭代并将非空白项目分配给新数组?
String test = "John, Jane";
//Without using the test.Replace(" ", "");
String[] toList = test.Split(',', ' ', ';');
如何从阵列中删除空白条目?如何从阵列中删除空白条目
迭代并将非空白项目分配给新数组?
String test = "John, Jane";
//Without using the test.Replace(" ", "");
String[] toList = test.Split(',', ' ', ';');
使用的string.Split
,需要一个StringSplitOptions
过载:
String[] toList = test.Split(new []{',', ' ', ';'}, StringSplitOptions.RemoveEmptyEntries);
你可以把它们放在一个列表中,然后调用列表的指定者方法,或者使用LINQ你很可能只是选择非空白,并做阵列。
你会使用the overload of string.Split
which allows the suppression of empty items:
String test = "John, Jane";
String[] toList = test.Split(new char[] { ',', ' ', ';' },
StringSplitOptions.RemoveEmptyEntries);
甚至更好,你就不会创建一个新的阵列中的每个时间:
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
不修改列表,所以这应该是精细。
string[] result = toList.Where(c => c != ' ').ToArray();
string[] toList = test.Split(',', ' ', ';').Where(v => !string.IsNullOrEmpty(v.Trim())).ToArray();
尝试了这一点用一点LINQ:
var n = Array.FindAll(test, str => str.Trim() != string.Empty);
如果分离器后面有一个空格,你可以将其包含在分隔符:
String[] toList = test.Split(
new string[] { ", ", "; " },
StringSplitOptions.None
);
如果分隔符也没有尾随空格,那么也可以包括这些:
String[] toList = test.Split(
new string[] { ", ", "; ", ",", ";" },
StringSplitOptions.None
);
注意:如果字符串包含真空项目,它们将被保留。即"Dirk, , Arthur"
将不会产生与"Dirk, Arthur"
相同的结果。
感谢这么多观点,喜欢它。 – Rod 2011-01-25 21:05:30