检测字符串是否在C#中包含多个连续重复字符的最有效方法是什么?

例如,用户输入“我喜欢这篇文章!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!”

连续的重复感叹号“!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!” 应该被发现。

以下正则表达式将检测重复的字符。 您可以将数字增加或将其限制为特定字符以使其更加健壮。

int threshold = 3; string stringToMatch = "thisstringrepeatsss"; string pattern = "(\\w)\\" + threshold" + "+"; Regex r = New Regex(pattern); Match m = r.Match(stringToMatch); While(m.Success) { Console.WriteLine("character passes threshold " + m.ToString()); m = m.NextMatch(); } 

这是一个函数示例,它搜索指定长度的连续字符序列,并忽略空格字符:

  public static bool HasConsecutiveChars(string source, int sequenceLength) { if (string.IsNullOrEmpty(source)) return false; if (source.Length == 1) return false; int charCount = 1; for (int i = 0; i < source.Length - 1; i++) { char c = source[i]; if (Char.IsWhiteSpace(c)) continue; if (c == source[i+1]) { charCount++; if (charCount >= sequenceLength) return true; } else charCount = 1; } return false; } 

编辑固定范围错误:/

可以在O(n)轻松完成:对于每个字符,如果前一个字符与当前字符相同,则增加一个临时计数。 如果不同,请重置临时计数。 在每个步骤中,根据需要更新全局。

对于abbccc你得到:

 a => temp = 1, global = 1 b => temp = 1, global = 1 b => temp = 2, global = 2 c => temp = 1, global = 2 c => temp = 2, global = 2 c => temp = 3, global = 3 => c appears three times. Extend it to get the position, then you should be able to print the "ccc" substring. 

您可以将其扩展为相当容易的起始位置,我会留给您。

这是一个快速的解决方案,我精心制作了一些额外的重复项,以便进行测量。 正如其他人在评论中指出的那样,一些重复文件将完全合法,因此您可能希望将标准缩小到标点符号而不仅仅是字符。

 string input = "I loove this post!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!aa"; int index = -1; int count =1; List dupes = new List(); for (int i = 0; i < input.Length-1; i++) { if (input[i] == input[i + 1]) { if (index == -1) index = i; count++; } else if (index > -1) { dupes.Add(input.Substring(index, count)); index = -1; count = 1; } } if (index > -1) { dupes.Add(input.Substring(index, count)); } 

我认为更好的方法是创建一个数组,数组中的每个元素都负责一个字符串彼此相邻,例如first aa,bb,cc,dd。 此数组构造在每个元素上都为0。

解决此问题是对此字符串和更新数组值的for。 接下来,您可以根据需要分析此数组。

示例:对于string:bbaaaccccdab,您的结果数组将是{2,1,3},因为’aa’可以找到2次,’bb’可以找到一次(在字符串的开头),’cc’可以找到三次。

为什么’cc’三次? 因为’cc’cc&c’cc’c&cc’cc’。

使用LINQ! (对于一切,不只是这个)

 string test = "aabb"; return test.Where((item, index) => index > 0 && item.Equals(test.ElementAt(index))); // returns "abb", where each of these items has the previous letter before it 

要么

 string test = "aabb"; return test.Where((item, index) => index > 0 && item.Equals(test.ElementAt(index))).Any(); // returns true