English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C Language Basic Tutorial

C Language Flow Control

C Language Functions

C Language Arrays

C Language Pointers

C Language Strings

C Language Structure

C Language File

C Others

C Language Reference Manual

C program to find character occurrence times in string

Comprehensive Collection of C Programming Examples

In this example, you will learn to find the occurrence times of a character in a string.

To understand this example, you should understand the followingC programmingTopic:

Find character occurrence times in string

#include <stdio.h>
int main() {
    char str[1000], ch;
    int count = 0;
    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);
    printf("Enter a character to find its occurrence times: ");
    scanf("%c", &ch);
    for (int i = 0; str[i] != '\0'; ++i) {
        if (ch == str[i])
            ++count;
    }
    printf("%c occurrence times = %d", ch, count);
    return 0;
}

Output result

Enter a string: This website is awesome.
Enter a character to find its occurrence times: e
e occurrence times= 4

In this program, the string entered by the user is stored in str.

Then, ask the user to input the character to find its occurrence count. This is stored in the variable ch.

Then, use a for loop to traverse the characters of the string. In each iteration, if the character in the string equals ch, count is incremented1.

Finally, print the number of occurrences stored in the variable count.

Comprehensive Collection of C Programming Examples