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

前端 未结 6 1355
無奈伤痛
無奈伤痛 2021-02-15 22:24

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

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

6条回答
  •  [愿得一人]
    2021-02-15 23:08

    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
    

提交回复
热议问题