我有一串由空格分隔的单词。如何根据单词长度将字符串拆分为单词列表?
示例
input:
" aa aaa aaaa bb bbb bbbb cc ccc cccc cccc bbb bb aa "
output :
List 1 = { aa, bb, cc} List 2 = { aaa, bbb, ccc} List 3 = { aaaa, bbbb, cccc}
最佳答案
您可以使用 Where
来查找与谓词匹配的元素(在本例中,具有正确的长度):
string[] words = input.Split();
List<string> twos = words.Where(s => s.Length == 2).ToList();
List<string> threes = words.Where(s => s.Length == 3).ToList();
List<string> fours = words.Where(s => s.Length == 4).ToList();
或者,您可以使用 GroupBy
一次查找所有组:
var groups = words.GroupBy(s => s.Length);
您还可以使用 ToLookup
以便您可以轻松地索引以查找特定长度的所有单词:
var lookup = words.ToLookup(s => s.Length);
foreach (var word in lookup[3])
{
Console.WriteLine(word);
}
结果:
aaa bbb ccc
See it working online: ideone
In your update it looks like you want to remove the empty strings and duplicated words. You can do the former by using StringSplitOptions.RemoveEmptyEntries
and the latter by using Distinct
.
var words = input.Split((char[])null, StringSplitOptions.RemoveEmptyEntries)
.Distinct();
var lookup = words.ToLookup(s => s.Length);
输出:
aa, bb, cc
aaa, bbb, ccc
aaaa, bbbb, cccc
在线查看它:ideone
关于c# - 将字符串拆分为基于单词长度的列表 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11378338/