Find Number Of Occurrences Of a Character In a String C Program - Coding Bot

Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Tuesday, 27 December 2016

Find Number Of Occurrences Of a Character In a String C Program

This program will find out the number of occurrences of each character in a string. So for example, if we have a string "I AM" then here the frequency of occurrence of each of 'I','A','M' will be 1. The program will print the same. This code can be easily modified to account for uppercase characters separately. 


Here is the C Code to find the number of occurrences of a character in a string:


/* Double-Click To Select Code */
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
   char string[100];
   int c = 0, count[26] = {0};
 
   printf("Enter a string\n");
   gets(string);
 
   while (string[c] != '\0')
   {
      if (string[c] >= 'a' && string[c] <= 'z') 
         count[string[c]-'a']++; 
      c++;
   }
 
   for (c = 0; c < 26; c++)
   { 
      if (count[c] != 0)
         printf("%c occurs %d times in the entered string.\n",c+'a',count[c]);
   }
}

Output:


Find Number Of Occurrences Of a Character In a String C Program




Do you like this post? Please link back to this article by copying one of the codes below.

URL: HTML link code: Forum link code: