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

前端 未结 6 1976
旧时难觅i
旧时难觅i 2021-02-15 22:20

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

the consecutive duplicate exclamation mark \"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\" should b

6条回答
  •  遥遥无期
    2021-02-15 23:06

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

提交回复
热议问题