Count occurrences of a character in a given string with C.
#include <stdio.h>
int main()
{
char str[100];
char toSearch;
int i, count;
/* Input string and search character from user */
printf("Enter any string: ");
gets(str);
printf("Enter any character to search: ");
toSearch = getchar();
count = 0;
i = 0;
while (str[i] != '\0')
{
if (str[i] == toSearch)
{
count++;
}
i++;
}
printf("Total occurrence of '%c' = %d", toSearch, count);
return 0;
}
Output
Enter any string : Lear with Reza
Enter any character to search : e
Total occurrence of 'e' = 2
0 Comments