在lambda表达式中进行分割时如何忽略空白?



我有一个如下的字符串,

var str = '  test'
当我调用表达式 时
str.split(' ')  I end up with 2 items in an array.

我如何分割它并最终只有test,即在c#中有一个非空白空间的东西?

您可以使用StringSplitOptions过载:

var str = "  test    words cat  dog   ";
String[] words = str.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;
foreach(String word in words)
{
Console.WriteLine(word);
}
Console.WriteLine("Count: " + wordCount);

可能有一种更有效的方法,但这仍然解决了问题:

List<string> strings = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
int stringCount = strings.Count();

试试str.Trim().Split(' '),这将去掉前后空白。如果你想把" a string with words "变成["a", "string", "with", "words"],这将实现。

你仍然需要考虑到单词之间的额外空格,尽管

编辑:这是一个更好的答案(基本使用Regex或str.Split(' ', StringSplitOptions.RemoveEmptyEntries): https://stackoverflow.com/a/18410393/5278363