Replace consecutive characters with same single character

后端 未结 5 2572
执笔经年
执笔经年 2021-02-20 05:58

I was just wondering if there is a simple way of doing this. i.e. Replacing the occurrence of consecutive characters with the same character.

For eg: - if my string is \

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-20 06:25

    string myString = "something likeeeee tttthhiiissss";
    
    char prevChar = '';
    StringBuilder sb = new StringBuilder();
    foreach (char chr in myString)
    {
        if (chr != prevChar) {
            sb.Append(chr);
            prevChar = chr;
        }
    }
    

提交回复
热议问题