Example:
Input string: I love programming. I love CodeforWin.
Input character to search: o
Output total occurrences of 'o': 5
Required knowledge
Basic C programming, Loop, StringProgram to count total occurrences of character in string
/**
* C program to count all occurrences of a character in a given string
*/
#include <stdio.h>
#define MAX_SIZE 100 //Maximum size of the string
int main()
{
char string[MAX_SIZE];
char search;
int i, count;
/* Reads a string and character from user */
printf("Enter any string: ");
gets(string);
printf("Enter any character to search: ");
search = getchar();
count = 0;
for(i=0; string[i]!='\0'; i++)
{
/*
* If character is found in string then
* increment count variable
*/
if(string[i] == search)
{
count++;
}
}
printf("Total occurrence of '%c' = %d", search, count);
return 0;
}
Output
Enter any string: I love programming. I love CodeforWin.
Enter any character to search: o
Total occurrence of 'o' = 5
Enter any character to search: o
Total occurrence of 'o' = 5
Happy coding ;)
You may also like
- String programming exercises index.
- C program to find first occurrence of a character in a string.
- C program to find last occurrence of a character in a string.
- C program to remove first occurrence of a character from given string.
- C program to remove last occurrence of a character from given string.
- C program to remove all occurrence of a character from a given string.
- C program to find first occurrence of a word in a given string.
- C program to remove first occurrence of a word from given string.
- C program to count frequency of all characters in a given string.
- C program to find reverse of a given string.