Like Us On Facebook

Follow Us On Twitter

Drop Down Menu

Wednesday 24 July 2013

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

Hello Guys,
In this post, I'll explain how to find the number of occurrences of a character in a string, program for which is really very simple.

A string is C is defined to be sequence of characters terminated by the special character '\0'. The special character '\0' is called the Null Character and it is to indicate the end of a string.

Let us straight away understand the following program.

str is declared  to be a string variable of size 100. This length can be varied according to user. I have taken it to be 100 so that a sentence can be easily accommodated. Its work is to collect a string(input) from the user. 


ch is declared to be a variable of char type and it is to collect a character(input), the number of occurrences of which in str is to be found out. i and count are declared to be variable of int type. the variable i is used to traverse the characters in str and count is to collect the number of occurrences of ch in str(output).


After a string is accepted into str, a for loop is set up to traverse each character of the string. Within the body of the loop, each character of the string is checked against ch for equality.


In case of a match, the variable count is incremented. When this loop exits, the variable count will have the number of occurrences of the given character in the given string.



C Program To Find The Number Of Occurrences Of a Character In a String:



/* Double-Click To Select Code */

#include<stdio.h>
#include<conio.h>

void main()
{
char str[100], ch;
int i, count;

clrscr();
printf("Enter a String: ");
gets(str);
fflush(stdin);
printf("\nEnter a Character: ");
scanf("%c",&ch);

/* Finding the no. of occurrences of character 'ch' in 'str' begins */
count=0;

for(i=0 ; str[i]!='\0' ; i++)
if(str[i]==ch)
count++;

/* Find the no. of occurrences of 'ch' in 'str' ends */

printf("\nNo. of occurrences of '%c' in '%s' is %d",ch,str,count);
getch();
}

Program Output:

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


Please Comment If You Liked The Post.



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: