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?