About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Wednesday, September 4, 2013

C Program to Search occurrence of Character in String

Logic [ Algorithm ]
  1. Accept the String from the user.
  2. Also Accept the character to be searched
  3. String is stored as array of character , then scan each array elementwith entered character.
  4. If it matches then increment the Counter by 1 else go for another character.

#include<stdio.h>
#include<conio.h>

void main()
{
char str[20],ch;
int count=0,i;
clrscr();

printf("\nEnter a string : ");
scanf("%s",&str);

printf("\nEnter the character to be searched : ");
scanf("%c",&ch);

  for(i=0;str[i]!='';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);

getch();
}

Output :
First Run :
Enter a string : c4learn.blogspot.com
Enter the character to be searched : o
Occurence of character 'o' : 3

Second Run :
Enter a string : c4learn.blogspot.com
Enter the character to be searched : x
Character 'x'is not present

No comments: