Forgive the second answer - it's very separate to my other answer so I think it warrants a new one.
Your code (and my suggested solution too) has a bug - UTF16 surrogate pairs...
Here's an example:
// Unicode character 🀜
var fourCircles = char.ConvertFromUtf32(0x1F01C);
// string 🀜🀜🀜 (same character repeated 3 times)
var twelveCircles = fourCircles + fourCircles + fourCircles;
HasConsecutiveChars(twelveCircles, 3); // False
Each char instance is one code point - a surrogate pair is made up of two encoding values in special ranges. So although we would consider it one 'character' it is in fact 2
char instances in C#.
See here for a better explanation than I could ever put together.
The Unicode Standard defines a surrogate pair as a coded character representation for a single abstract character that consists of a sequence of two code units. The first value of the surrogate pair is the high surrogate, a 16-bit code value in the range of U+D800 through U+DBFF. The second value of the pair is the low surrogate, in the range of U+DC00 through U+DFFF.
Another slightly less weird bug is the following string:
Both of those strings also result in
False even though they should be
Strings are really hard - these bugs probably won't matter for you but it's always worth pointing out really obscure edge cases ;)
I should point out that I'm on my mac so I had to do my testing on ideone (mono) but results should be the same on windows too.
I couldn't resist trying to make a solution that works for all chars...
// using System;
// using System.Globalization;
// using System.Text;
public static bool HasConsecutiveChars(string source, int sequenceLength)
// omitted argument checking (see Heslacher's answer)
var charEnumerator = StringInfo.GetTextElementEnumerator(source);
var currentElement = string.Empty;
int count = 1;
if (currentElement == charEnumerator.GetTextElement())
if (++count >= sequenceLength)
count = 1;
currentElement = charEnumerator.GetTextElement();
Here's it working on ideone