What is the most efficient way to detect if a string contains a number of consecutive duplicate characters in C#?

The following regular expression would detect repeating chars. You could up the number or limit this to specific characters to make it more robust.

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

Here's and example of a function that searches for a sequence of consecutive chars of a specified length and also ignores white space characters:

    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;
    }

Edit fixed range bug :/

Tags:

C#

String