trying to calculate the number of letters in a string

travelmate81's Avatar, Join Date: Nov 2007
Newbie Member
hello people....i just started to learn C so im very new with it....
im trying to calculate to the number of letters that i have in a string
for example :
string = GoforEEeexpeRT
the result should be
the letter is E , 5 times.

so far i tried to this but im getting error when im trying to run it .
can someone help me with it, thanks in advance.

Code:
#include <stdio.h>
#define ABC 100
int main()
{
	char st[ABC];
	int a[ABC], i,j;
	
	printf("\nPlease enter the string\n");	
	for (i=0; i<ABC; i++)	 /* initialization */
		a[i]=0;	
	
	j=0;
    while (st[j]!='\0')
	{
		if (st[j]>='A'&& st[j]<='Z')
			st[j]=st[j]+32 ;
		j++;

	}
		i=0; 
		for(i=0;i<ABC;i++)
			for(k=i;k<ABC;k++)
			{
				if (st[k]==st[i])
					a[i]++;
			}

		while(
				i++;
		ch[i] = s[i];
		printf("the letter is %s\n", s);
	}
}

Last edited by shabbir; 24Nov2007 at 14:11.. Reason: Code block
Titus2go's Avatar, Join Date: Jul 2007
Newbie Member
Hi travelmate81,

Here is just a short solution to your problem.

Code:
#include <stdio.h>
#include <ctype.h>

#define SLENGTH 14

int count_occurrence(char word[], char letter);

main()
{
	int i, count;
	char word[SLENGTH], code;
	printf("Please enter a string: ");
	//read characters and put them into the array
	for(i = 0; i < SLENGTH; i++)
	{
		scanf("%c", &word[i]);
		//turn all the characters in word to lower case
		word[i] = tolower(word[i]);
	}
	//count the occurrence of each letter
	for(code='a';code<='z';code = code+1)
	{
		count = count_occurrence(word, code, SLENGTH);
	    if(count != 0)
			printf("The letter %c appeared %d times\n", code, count);
	}
}

int count_occurrence(char word[], char letter, int length)
{
	int i, count = 0;
	for(i = 0; i < length; i++)
		if(word[i] == letter)
			count++;
	return count;
}
I hope this helps, you can modify it if you want.
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Your program has an error. You have not defined the program correctly.

Here is the program to count all the strings in an array
Code: C
#define SLENGTH 26

int main()
{
    int i;
    char word[SLENGTH];
    int count[SLENGTH] = {0};
    printf("Please enter a string: ");

    scanf("%s", word);
    for(i = 0; i < SLENGTH && word[i] != '\0'; i++)
    {
        word[i] = tolower(word[i]);
        count[word[i]-'a']++;
    }
    for(i = 0; i < SLENGTH; i++)
    {
        if(count[i] != 0)
            printf("The letter %c appeared %d times\n", i+'a', count[i]);
    }
    getch();
}