In this article, we are going to learn How to count a character occurrence in a C string. We will count the occurrence of a character in a string if that character occurs n number of times in a string. We will use a fixed string and then we will ask users which character they want to count in this string.
Once the user will give the input character then we will search the character in this string and will print how many times that character appeared in this string. If the input character does not exist in the string then we will notify that character is not found in the string.
Here is the code program to do this logic.
#include <stdio.h>
int main()
{
char str[] = "DevEnum.com";
char ch;
printf("Please tell which character you want to find in %s : ",str);
scanf("%c",&ch);
int i, count = 0;
while(str[i] != '
#include <stdio.h>
int main()
{
char str[] = "DevEnum.com";
char ch;
printf("Please tell which character you want to find in %s : ",str);
scanf("%c",&ch);
int i, count = 0;
while(str[i] != '\0')
{
if(str[i] == ch)
count++;
i++;
}
if(count > 0)
{
printf("The Character %c occurs %d times in '%s'", ch, count, str);
}
else
printf("The Character %c did not occurs in %s", ch, str);
return 0;
}
')
{
if(str[i] == ch)
count++;
i++;
}
if(count > 0)
{
printf("The Character %c occurs %d times in '%s'", ch, count, str);
}
else
printf("The Character %c did not occurs in %s", ch, str);
return 0;
}
Output
Please tell which character you want to find in DevEnum.com : m
The Character m occurs 2 times in 'DevEnum.com'