Character Occurrence Counter in C

This snippet defines a function to count occurrences of a specific character in a string. It includes a main function that demonstrates the usage of this character counting function by counting how many times 'o' appears in the string 'hello world'. The result is printed to the standard output.
mail@pastecode.io avatar
unknown
c_cpp
a month ago
408 B
2
Indexable
Never
#include <stdio.h>

int count_occurrences(char str[], char ch) {
    int count = 0;
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == ch) {
            count++;
        }
    }
    return count;
}

int main() {
    char str[] = "hello world";
    char ch = 'o';
    
    int count = count_occurrences(str, ch);
    printf("Character '%c' occurred %d times\n", ch, count);
    
    return 0;
}
Leave a Comment