How To Count The Number Of Occurrences Of a Character in a String in C
In this tutorial, we are going to see how to count the number of occurrences of a character in a string in C using For loop.
In the code below, we count the number of occurrences of each character in a string. To do this, we first create an array, the idea here is to store the number of occurrences relative to the ASCII value of that character. For example, the occurrence of “A” would be stored as [65] because the ASCII value of A is 65.
How To Count The Number Of Occurrences Of a Character in a String in C
#include <stdio.h> int main() { char c, str[100]; int i, occurrence = 0; printf("Enter a string: "); gets(str); printf("Enter a character: "); scanf("%c",&c); for(i = 0; str[i] != '\0'; ++i) { if(str[i] == c) ++occurrence; } printf("Number of occurrences of %c is %d", c, occurrence); return 0; }
Output:
Enter a string: StackHowTo Enter a character: o Number of occurrences of o is 2