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

前端 未结 6 1973
旧时难觅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:16

    Here is a quick solution I crafted with some extra duplicates thrown in for good measure. As others pointed out in the comments, some duplicates are going to be completely legitimate, so you may want to narrow your criteria to punctuation instead of mere characters.

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

提交回复
热议问题