如何從陣列中刪除空白條目?如何從陣列中刪除空白條目
迭代並將非空白項目分配給新數組?
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