Replace consecutive characters with same single character

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.

This should do it:

var regex = new Regex("(.)\\1+");
var str = "something likeeeee!! tttthhiiissss";

Console.WriteLine(regex.Replace(str, "$1")); // something like! this

The regex will match any character (.) and \\1+ will match whatever was captured in the first group.


string myString = "something likeeeee tttthhiiissss";

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

Tags:

C#