Posted By:
23 Jun, 2013 1:13 pm PDT

Strings in C

How can you find the occurrences of a character in a string?

This program is used to count the frequency of characters in a string i.e. which character is present how many times in a string. This program works for lower case letters. To count the characters we use the following code: 

while ( string[c] != '\0' )


    /* Considering characters from 'a' to 'z' only */


    if ( string[c] >= 'a' && string[c] <= 'z' )






for ( c = 0 ; c < 26 ; c++ )


    if( count[c] != 0 )

        printf("%c - %d times.\n",c+'a',count[c]);


Please see the video for more details

Was it useful?  

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.

void main()
char str[100], ch;
int i, count;
printf("Enter a String: ");
printf("\nEnter a Character: ");
/* Finding the no. of occurrences of character 'ch' in 'str' begins */
for(i=0 ; str[i]!='\0' ; i++)
/* Find the no. of occurrences of 'ch' in 'str' ends */
printf("\nNo. of occurrences of '%c' in '%s' is %d",ch,str,count);

Was it useful?  

Please login to reply to this problem.

Related Problems on Fixoncloud