trying to calculate the number of letters in a string

Discussion in 'C' started by travelmate81, Nov 23, 2007.

1. travelmate81New Member

Joined:
Nov 23, 2007
Messages:
1
0
Trophy Points:
0
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;

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 a moderator: Nov 24, 2007
2. Titus2goNew Member

Joined:
Jul 19, 2007
Messages:
1
0
Trophy Points:
0
Occupation:
Self Emply
Location:
Bellevue, WA
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;
//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.

Joined:
Jul 12, 2004
Messages:
15,326
377
Trophy Points:
83
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:
```#define SLENGTH 26

int main()
{
int i;
char word[SLENGTH];
int count[SLENGTH] = {0};

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