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

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

    Use LINQ! (For everything, not just this)

    string test = "aabb";
    return test.Where((item, index) => index > 0 && item.Equals(test.ElementAt(index)));
    // returns "abb", where each of these items has the previous letter before it
    

    OR

    string test = "aabb";
    return test.Where((item, index) => index > 0 && item.Equals(test.ElementAt(index))).Any();
    // returns true
    

提交回复
热议问题