can someone advise how can I print the repeating letter with its final count/occurance once? I have the following code and after it the output but I want the output to be: 2a, 1b, 3c instead of 1a, 2a, 1b, 1c, 2c, 3c
#include <unistd.h>
#include <stdio.h>
int str_len(char *str)
{
int i = 0;
while(str[i])
i++;
return(i);
}
void count_alpha(char *str)
{
int tab[26] = {0};
int i = 0;
int len = str_len(str);
while(str[i])
{
if (str[i] >= 'a' && str[i] <= 'z')
{
if(tab[str[i] - 'a'] == 0)
tab[str[i] - 'a'] = 1;
else
tab[str[i] - 'a']++;
}
if(tab[str[i] - 'a'] < len)
printf("%d%c, ", tab[str[i] - 'a'], str[i]);
i++;
}
}
int main()
{
char str[] = "aabccc";
count_alpha(str);
return(0);
}
output
1a, 2a, 1b, 1c, 2c, 3c, %
i need a simple way to write the letter just once with its final occurrence count
Move this part:
Out of the while loop and into a for loop of its own:
Misc other problems:
Use const correctness.
void count_alpha(char *str)->void count_alpha(const char *str).Arithmetic on symbol values such as
str[i] - 'a'is strictly speaking not well-defined and isn't guaranteed to work (except for the symbols'0'to'9'). For a fully portable and strictly conforming program, you would instead doint tab[256] = {0};and then access it with an index corresponding to the symbol value. (Would also make the algorithm case-sensitive and faster, at the expense of stack memory use.)This part here is nonsense, just remove it since it fills no purpose:
Making your own function
str_leninstead of calling standardstrlenjust makes your program much slower for no good reason.return(i);The parenthesis around the return value is pointless.