×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

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

By IncludeHelp Last updated : December 26, 2023

Problem statement

Given a string, write a C program to find the frequency of a character in the given string.

Finding the frequency of a character in a string

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

In this example, we have used the following C language topics that you should learn:

C String Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.