A PHP Error was encountered

Severity: 8192

Message: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated

Filename: libraries/Filtered_db.php

Line Number: 23

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

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

0

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!".

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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!"

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now