Compress string
Given a non-empty string, write a method that returns it in compressed format.
Expected input and output
CompressString("kkkktttrrrrrrrrrr") → "k4t3r10"
CompressString("p555ppp7www") → "p153p371w3"
using System;
namespace CSharpExercises
{
class Program
{
public static string CompressString(string str)
{
var count = 0;
var last = str[0];
var newStr = string.Empty;
foreach (var s in str)
{
if (s == last)
{
count++;
}
else
{
newStr += last.ToString() + count;
last = s;
count = 1;
}
}
newStr += last.ToString() + count;
return newStr;
}
static void Main(string[] args)
{
Console.WriteLine(CompressString("aaaabbcccccdaa")); //a4b2c5d1a2
Console.WriteLine(CompressString("948kro")); //914181k1r1o1
Console.WriteLine(CompressString("$999j*#jjjfYyyy")); //$193j1*1#1j3f1Y1y3
}
}
}