c# - 将字符串拆分为基于单词长度的列表 C#

标签 c# string list

我有一串由空格分隔的单词。如何根据单词长度将字符串拆分为单词列表?

示例

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/

相关文章:

c++ - 将 std::__cxx11::string 转换为 std::string

java - 返回 HashSet 中对象的连接某些字段的字符串

python - 如何生成 3 个字符前缀的唯一列表

python - 从字典中的列表中删除项目

c# - SignalR 替换消息队列

c# - 将项目添加到 StackPanel 时的事件处理程序?

c++ - 为什么 pangram missing letter 函数不返回任何内容?

c# - 检查值是否已经在列表属性中

c# - 为什么 ReSharper 建议在动态类型上可能出现 NullReferenceException?

c# - 无法在 Open Xml 中使用现有段落样式