LINQ 从字符串中连续查找 3 次以上


string x = "abcdeffffaaaasdfhfgjhfghzxxxx";

如果某个字母连续出现超过一定时间,我如何从字符串中获取字符,等等,如果任何字母连续出现超过 3 次,您将在集合中获得 4 个"a"元素。是否可以使用 LINQ?

我会选择正则表达式,但如果你真的想使用 LINQ,我会将你的字符序列分组为相同字符的组,并计算每个组中的元素数。

待办事项:确定 A a à à à Ã ä 是相同的"字母"还是不同的"字母"。使用StringCompare.InvariantCultureIgnoreCase等来克服这个问题

var CharacterCounts = sourceString       // get your source string as sequence of char
.GroupBy(letter => letter           // group them into groups with same letter
.Select(group => new                // from every group count the number of elements
{
Char = group.Key,
Count = group.Count(),
}

要知道是否有任何字母出现超过某个数字:

bool someLettersOften = characterCounts
.Where(characterCount => characterCount.Count > 3)
.Any();

要获取经常出现的所有字母,请执行以下操作:

var oftenUsedLetters = characterCounts
.Where(characterCount => characterCount.Count > 3)
.Select(characterCount => characterCount.Character);

最新更新