How to count occurrences of all characters in a string with C

1 Answer

0 votes
#include <stdio.h>

#define SIZE 256

void count_occurrences(char s[], char occurrences[]) {
	int i  = 0;
    while(s[i]) {
        occurrences[(int)s[i]]++;
        i++;
    }
}

int main() {
	char s[] = "c c++ c# java php python cobol";
	char occurrences[SIZE] = {0};
	
	count_occurrences(s, occurrences);
	for (int i = 0; i < SIZE; i++) 
		if (occurrences[i] != 0)
			printf("%c - %d times\n", i, occurrences[i]);
	
    return 0;
}
 
 
      
/*
run:
   
  - 6 times
# - 1 times
+ - 2 times
a - 2 times
b - 1 times
c - 4 times
h - 2 times
j - 1 times
l - 1 times
n - 1 times
o - 3 times
p - 3 times
t - 1 times
v - 1 times
y - 1 times

*/

 



answered Jul 5, 2020 by avibootz

Related questions

1 answer 186 views
1 answer 179 views
1 answer 194 views
1 answer 103 views
1 answer 183 views
1 answer 148 views
...