Write a C program to count all occurrences of a character in a string using loop. How to find total occurrences of a given character in a string using for loop in C programming. Logic to count total occurrences of a character in a given string in C program.
Example
Input
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, String
Must know – Program to search occurrences of a character in string
Logic to count occurrences of a character in given string
Below is the step by step descriptive logic to count occurrences of a character in given string.
- Input a string from user, store it in some variable say str.
- Input character to search occurrences, store it in some variable say toSearch.
- Initialize count variable with 0 to store total occurrences of a character.
- Run a loop from start till end of string str. The loop structure should look like while(str[i] != ‘\0’).
- Inside the loop if current character of str equal to toSearch, then increment the value of count by 1.
Program to count total occurrences of character in string
Output
Enter any string: I love programming. I love Codeforwin. Enter any character to search: o Total occurrence of 'o' = 5
Happy coding
Recommended posts
- 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.