C

How To Count The Number Of Occurrences Of a Character in a String in C

In this tutorial, we are going to see how to count the number of occurrences of a character in a string in C using For loop.

In the code below, we count the number of occurrences of each character in a string. To do this, we first create an array, the idea here is to store the number of occurrences relative to the ASCII value of that character. For example, the occurrence of “A” would be stored as [65] because the ASCII value of A is 65.
100-multiple-choice-questions-in-c-programming100 Multiple Choice Questions In C Programming – Part 1This collection of 100 Multiple Choice Questions and Answers (MCQs) In C Programming : Quizzes & Practice Tests with Answer focuses on “C Programming”.  …Read More

How To Count The Number Of Occurrences Of a Character in a String in C
#include <stdio.h>

int main()
{
   char c, str[100];
   int i, occurrence = 0;
   
   printf("Enter a string: ");
   gets(str);
   
   printf("Enter a character: ");
   scanf("%c",&c);
   
   for(i = 0; str[i] != '\0'; ++i)
   {
       if(str[i] == c)
           ++occurrence;
   }
   
   printf("Number of occurrences of %c is %d", c, occurrence);
   return 0;
}

Output:

Enter a string: StackHowTo
Enter a character: o
Number of occurrences of o is 2

 

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *