C program to count occurrences of a character in a string

Write a C program to count all occurrences of a character in a string using loop. How to find total occurrences of a given character in a string using for loop in C programming. Logic to count total occurrences of a character in a given string in C program.

Required knowledge

Basic C programming, C for loop, Array, functions, Strings

Logic to count occurrences of a character in given string

Below is the step by step descriptive logic to count occurrences of a character in given string.

  1. Input a string from user, store it in some variable say str.
  2. Input character to search occurrences, store it in some variable say toSearch.
  3. Initialize count variable with 0 to store total occurrences of a character.
  4. Run a loop from start till end of string str. The loop structure should look like while(str[i] != '\0').
  5. Inside the loop if current character of str equal to toSearch, then increment the value of count by 1.

Program to count total occurrences of character in string



 
/**
 * C program to count all occurrences of a character in a given string
 */

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

int main()
{
    char str[MAX_SIZE];
    char toSearch;
    int i, count;

    /* Input string and search character from user */
    printf("Enter any string: ");
    gets(str);
    printf("Enter any character to search: ");
    toSearch = getchar();

    count = 0;
    i=0;
    while(str[i] != '\0')
    {
        /*
         * If character is found in string then
         * increment count variable
         */
        if(str[i] == toSearch)
        {
            count++;
        }

        i++;
    }

    printf("Total occurrence of '%c' = %d", toSearch, count);

    return 0;
}



Output:

Enter any string: I love program coding
Enter any character to search: o
Total occurrence of 'o' = 3
Process returned 0 (0x0) execution time : 15.454 s



Instagram