Replace consecutive characters with same single character

后端 未结 5 2569
执笔经年
执笔经年 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:41

    How about:

    s = new string(s
         .Select((x, i) => new { x, i })
         .Where(x => x.i == s.Length - 1 || s[x.i + 1] != x.x)
         .Select(x => x.x)
         .ToArray());
    

    In english, we are creating a new string based on a char[] array. We construct that char[] array by applying a few LINQ operators:

    1. Select: Capture the index i along with the current character x.
    2. Filter out charaters that are not the same as the subsequent character
    3. Select the character x.x back out of the anonymous type x.
    4. Convert back to a char[] array so we can pass to constructor of string.

提交回复
热议问题