C program to count all 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. Program to calculate total occurrences of a character in a given string.

Example:
Input string: I love programming. I love CodeforWin.
Input character to search: o
Output total occurrences of 'o': 5

Required knowledge

Basic C programming, Loop, String

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 size of the string

int main()
{
    char string[MAX_SIZE];
    char search;
    int i, count;

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

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

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

    return 0;
}


Output
Enter any string: I love programming. I love CodeforWin.
Enter any character to search: o
Total occurrence of 'o' = 5

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment