String compression implementation in C# I wrote a method that reduces a string like aabcccccaaa to a2b1c5a3

My implementation:

string Compress(string str)
{
    StringBuilder builder = new StringBuilder();
    using(TextReader reader = new StringReader(str))
    {
        while(reader.Peek() != - 1){
            char c = (char)reader.Read();
            int n = 1;
            while(reader.Peek() == c) {
                reader.Read();
                n++;
            }
            builder.AppendFormat("{0}{1}",c,n);
        }
    }
    return builder.ToString();
}


What do you think about this, is there a better way to do this?
You can use a regular expression to match a range of repeated characters and replace it with the character and the count:

public static string Compress(string str) {
  return Regex.Replace(str, @"(.)\1*", m =&gt; m.Groups[1].Value + m.Value.Length);
}


If that is better or not is up for debate, but it is at least a lot shorter.

You can also make it simpler using a regular loop and access the characters by index instead of using a StringReader. That makes it easier to compare the characters next to each other:

public static string Compress(string str) {
  StringBuilder builder = new StringBuilder();
  for (int i = 1, cnt = 1; i &lt;= str.Length; i++, cnt++) {
    if (i == str.Length || str[i] != str[i - 1]) {
      builder.Append(str[i - 1]).Append(cnt);
      cnt = 0;
    }
  }
  return builder.ToString();
}