C Program to Search occurrence of Character in String
Search whether character is present in the string or not :
Logic [ Algorithm ]:
- Accept the String from the user.
- Also Accept the character to be searched
- String is stored as array of character , then scan each array element with entered character.
- If it matches then increment the Counter by 1 else go for another character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include<stdio.h> #include<conio.h> int main() { char str[20], ch; int count = 0, i; printf("\nEnter a string : "); scanf("%s", &str); printf("\nEnter the character to be searched : "); scanf("%c", &ch); for (i = 0; str[i] != '\0'; i++) { if (str[i] == ch) count++; } if (count == 0) printf("\nCharacter '%c'is not present", ch); else printf("\nOccurence of character '%c' : %d", ch, count); return (0); } |
Output :
1 2 3 4 5 6 7 8 9 |
<strong>First Run :</strong> Enter a string : c4learn.blogspot.com Enter the character to be searched : o Occurence of character 'o' : 3 <strong>Second Run :</strong> Enter a string : c4learn.blogspot.com Enter the character to be searched : x Character 'x'is not present |
[toggle title=”Download Program”]Download[/toggle]