Count Occurrences of a Character in a String in C

In C, we can count the occurrences of a character in a string using loops, standard library functions, or pointer-based approaches. This is done by iterating through the string and keeping track of how many times the target character appears.

In this tutorial, we will explore different methods to achieve this with clear explanations and example programs.


Examples to Count Character Occurrences

1. Counting Occurrences Using a for Loop

In this example, we will traverse the string using a for loop and count the number of times a specified character appears.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[] = "hello world";
    char target = 'o';
    int count = 0;

    // Loop through the string to count occurrences of target character
    for (int i = 0; str[i] != '\0'; i++) {
        if (str[i] == target) {
            count++;
        }
    }

    printf("Character '%c' appears %d times in the string.\n", target, count);
    return 0;
}

Explanation:

  1. We declare a string str[] = "hello world" and a target character 'o' to be counted.
  2. We initialize a counter variable count = 0 to store the number of occurrences.
  3. The for loop iterates through the string until it reaches the null terminator ('\0').
  4. Inside the loop, we check if str[i] is equal to target.
  5. If a match is found, we increment the count variable.
  6. Finally, we print the total count of occurrences using printf().

Output:

Character 'o' appears 2 times in the string.

2. Counting Occurrences Using while Loop

In this example, we will use a while loop to iterate through the string and count occurrences of a specific character.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[] = "programming in C";
    char target = 'g';
    int count = 0, i = 0;

    // Using while loop to count occurrences of target character
    while (str[i] != '\0') {
        if (str[i] == target) {
            count++;
        }
        i++;
    }

    printf("Character '%c' appears %d times in the string.\n", target, count);
    return 0;
}

Explanation:

  1. We declare a string str[] = "programming in C" and a target character 'g'.
  2. We initialize the counter count = 0 and index i = 0.
  3. The while loop runs until str[i] reaches the null terminator ('\0').
  4. If str[i] matches target, we increment count.
  5. We increment i in each iteration to move to the next character.
  6. Finally, the count is printed using printf().

Output:

Character 'g' appears 2 times in the string.

3. Counting Occurrences Using strchr()

In this example, we will use the strchr() function from string.h to locate occurrences of a character in a string.

main.c

</>
Copy
#include <stdio.h>
#include <string.h>

int main() {
    char str[] = "C programming is fun";
    char target = 'm';
    int count = 0;
    char *ptr = str;

    // Using strchr() to find occurrences
    while ((ptr = strchr(ptr, target)) != NULL) {
        count++;
        ptr++; // Move to next character
    }

    printf("Character '%c' appears %d times in the string.\n", target, count);
    return 0;
}

Explanation:

  1. We declare a string str[] = "C programming is fun" and a target character 'm'.
  2. We initialize a pointer ptr to point to the start of str.
  3. The strchr() function searches for the first occurrence of target and returns a pointer to it.
  4. If a match is found, we increment count and move ptr forward to continue searching.
  5. The loop repeats until strchr() returns NULL, indicating no more occurrences.
  6. Finally, we print the total count.

Output:

Character 'm' appears 2 times in the string.

Conclusion

We explored multiple ways to count character occurrences in a string in C:

  1. Using a for loop to iterate through the string.
  2. Using a while loop for iteration.
  3. Using the strchr() function to find occurrences efficiently.