English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to find the occurrence times of a character in a string.
To understand this example, you should understand the followingC programmingTopic:
#include <stdio.h> int main() { char str[1000], ch; int count = 0; printf("Enter a string: "); fgets(str, sizeof(str), stdin); printf("Enter a character to find its occurrence times: "); scanf("%c", &ch); for (int i = 0; str[i] != '\0'; ++i) { if (ch == str[i]) ++count; } printf("%c occurrence times = %d", ch, count); return 0; }
Output result
Enter a string: This website is awesome. Enter a character to find its occurrence times: e e occurrence times= 4
In this program, the string entered by the user is stored in str.
Then, ask the user to input the character to find its occurrence count. This is stored in the variable ch.
Then, use a for loop to traverse the characters of the string. In each iteration, if the character in the string equals ch, count is incremented1.
Finally, print the number of occurrences stored in the variable count.