C Language Example - Find the Number of Occurrences of a Character in a String
Find the starting position of a character in a string (index value starts from 0).
Example
#include <stdio.h>
int main()
{
char str[1000], ch;
int i, frequency = 0;
printf("Input string:");
fgets(str, (sizeof str / sizeof str[0]), stdin);
printf("Enter the character to find:");
scanf("%c",&ch);
for(i = 0; str[i] != '\0'; ++i)
{
if(ch == str[i])
++frequency;
}
printf("The character %c appears %d times in the string.", ch, frequency);
return 0;
}
The output result is:
输入字符串: example 输入要查找的字符: o 字符 o 在字符串中出现的次数为 2other extensions