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

Strings in C

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


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' )

        count[string[c]-'a']++;

   

    c++;

}

 

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.

#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();
}

Was it useful?  




Please login to reply to this problem.