Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

For example, a user entered "I love this post!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

the consecutive duplicate exclamation mark "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" should be detected.

like image 204
silent Avatar asked Apr 19 '10 21:04

silent


2 Answers

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();
         }
like image 88
ChickenMilkBomb Avatar answered Oct 14 '22 08:10

ChickenMilkBomb


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 :/

like image 42
Pop Catalin Avatar answered Oct 14 '22 09:10

Pop Catalin