Sunday, September 7, 2014

find how many times a character appears in a string


Problem

write a c program that will ask the user to input a character and then the program will check whether the character (how many times) exists in the following string or not.

Note: use pointers to find the character in the string character by character.

Solution - Code

#include<stdio.h>
#include<conio.h>
int countchar(char *p, char a);
main()
{
 int count;
 char a;
 char p[]="OMG! its hot.";
 printf("Enter the character : ");
 scanf("%c",&a);
 count = countchar(p,a);
 printf("\n\nCharacter %c occured in the array %d times.\n",a,count);
 system("pause");
}
int countchar(char *p, char a)
{
 int count=0;
 while (*p != '\0')
 {
  if (a == *p)
   count++;
  p++;
 }
 return (count);
}

Sample Output


find character in a string

No comments :

Post a Comment

Note: Only a member of this blog may post a comment.

Copyright 2017. All Rights Reserved. Privacy Policy / Terms And Conditions / Sitemap / Contact