user2974944 user2974944 - 6 days ago 6
C# Question

count occurrences of values in a row special printing

I have a row like this: a a b b b a b a a b b
I need code to print this out: 2a 3b 1a 1b 2a 2b

How to do that in c# or php or any programming language. Maybe excel solution?

EDIT
I need the values to be counted like this: there are 2 of a then 3 of b then 1 of a then 1 of b then 2 of a then 2 of b.
I don't need to count occurrences of a and b in total.
EDIT 2
I did this with the row of strings:
for (int i = 0; i < ss.Length;i++ )
{

if (i == 0) {
br =1;
line=br.ToString()+"*" + ss[i];
}
else
{
if (ss[i] != ss[i - 1])
{
br = 1;
line += br.ToString() + "*" + ss[i];
}
else
{

br = br + 1;
line = br.ToString() + "*" + ss[i];
}
}
}


and for the string a b b a, I got 2b 1a, i lost first a somewhere

Answer

Here is a RegEx approach

string input = "aabbbabaabb";
string result = string.Concat(Regex.Matches(input, @"(.)\1*", RegexOptions.None)
                      .Cast<Match>()
                      .Select(x => string.Concat(x.Length, x.Value.First())));
Comments