## 4.09.2012

### Position of character and How many times character repeat in string

Q. write a C program to accept a string from user and after that accept a single character from user and search whether this character include in string or not if is is include then find out the position of character and also calculate, how many times character repeat?

For example:

Entered string : This is C programming
Entered character for search: p

Position of p in string : 11
Repeation of p in string : 1

Ans.

/*c program for search character and if is include then how many times present in string*/
#include<stdio.h>
#include<conio.h>
int searchChar(char [], char);
int repeatChar(char [], char);
int main()
{
char str[100];
char search;
int count,repeat,posi;
printf("Enter any string : ");
for(count=0; ((str[count]=getchar())!='\n'); ++count);
str[count+1]='\0';
printf("Enter character for search : ");
scanf("%c", &search);
posi = searchChar(str,search);
repeat = repeatChar(str,search);
if(posi == -1)
else
{
printf("\nPosition of %c in string = %d\n",search,posi+1);
printf("\nRepeation of %c in string = %d\n",search,repeat);
}
getch();
return 0;
}

/*function for search character*/
int searchChar(char str[], char ch)
{
int i;
for(i=0; str[i]!='\0'; i++)
{
if(str[i]==ch)
return i;
}
return -1;
}

/*function for calculate frequency of character*/
int repeatChar(char str[], char ch)
{
int i,rep=0;
for(i=0; str[i]!='\0'; i++)
{
if(str[i]==ch)
rep++;
}
return rep;
}

/**************Output**************/

 Screen shot for search character in string and find its frequency

Related programs: