How to count occurrences of a character in a string with C

1 Answer

0 votes
#include <stdio.h>

int count_occurrences(char s[], char ch) {
	int count = 0, i  = 0;
    while(s[i]) {
        if(s[i] == ch) {
            count++;
        }
        i++;
    }
	return count;
}

int main() {
	char s[] = "c c++ c# java php python cobol";
	
	printf("%d\n", count_occurrences(s, 'c'));
	printf("%d\n", count_occurrences(s, 'p'));
	
    return 0;
}
 
 
      
/*
run:
   
4
3

*/

 



answered Jul 4, 2020 by avibootz

Related questions

1 answer 151 views
2 answers 248 views
1 answer 202 views
1 answer 232 views
1 answer 182 views
1 answer 145 views
1 answer 109 views
...