Home » C programs » C string programs

C program to find the frequency of a character in a string

In this program, we will learn how to find occurrence of a particular character in a string using C program?

Here, we are reading a character array/string (character array is declaring with the maximum number of character using a Macro MAX that means maximum number of characters in a string should not more than MAX (100), then we are reading a character to find the occurrence and counting the characters which are equal to input character.

For example:
If input string is "Hello world!" and we want to find occurrence of 'l' in the string, output will be 'l' found 3 times in "Hello world!".

Program to find occurrence of a character in an input string in C



#include <stdio.h>
#define MAX	100

int main()
{
	char str[MAX]={0};
	char ch;
	int count,i;
	
	
	//input a string
	printf("Enter a string: ");
	scanf("%[^\n]s",str); //read string with spaces
	
	getchar(); // get extra character (enter/return key)
	
	//input character to check frequency
	printf("Enter a character: ");
	ch=getchar();
	
	//calculate frequency of character 
	count=0;
	for(i=0; str[i]!='\0'; i++)
	{
		if(str[i]==ch)
			count++;
	}
	
	printf("\'%c\' found %d times in \"%s\"\n",ch,count,str);
	
	return 0;	
}

Output

First run
Enter a string: Hello world!
Enter a character: l
'l' found 3 times in "Hello world!"

Second run
Enter a string: Hello world!
Enter a character: x
'x' found 0 times in "Hello world!"





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.