Given an input string of characters write a function that returns another string that has the frequency of each consecutive character followed by the character itself.
eg:
aabbbbbzzzzzzzzzz — a2b5z10
aaabcdf — a3b1c1d1f1
Algorithm
- Iterate through each character of the string.
- If character is same as previous place character, then increment counter.
- Else
- add character to the output string.
- Add counter to the output string.
- Set counter = 0
- Return the output string.
Let’s analyze the full program to solve the problem.
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
void string_count_occurance (char *in, char *out)
{
int size = strlen (in);
int index = 0;
int count = 1;
char c = in[0];
for (int i = 1; i < size; i++)
{
if (in[i] != c) {
out[index++] = c;
out[index++] = '0' + count;
count = 1;
c = in[i];
}
else
{
count++;
}
}
out[index++] = c;
out[index++] = '0' + count;
out[index] = '\0';
}
int main ()
{
char in[100];
char out[100];
printf ("Enter the String \n");
scanf ("%s", in);
string_count_occurance (in, out);
printf ("Input String: %s \n", in);
printf ("Output String: %s \n", out);
}
Let’s analyze the output of above function.
Enter the String
a
Input String: a
Output String: a1
--------------------------------------------------------
Enter the String
abcdef
Input String: abcdef
Output String: a1b1c1d1e1f1
--------------------------------------------------------
Enter the String
aaabcdfzzzzz
Input String: aaabcdfzzzzz
Output String: a3b1c1d1f1z5