carraysc-stringsstrcmpstrchr

How do I count how many times a letter appears in a string? C programming


I am trying to write a program to tell me how many 'e' letters are in the phrase "Yesterday, all my troubles seemed so far away". I am trying to do this using strcmp function and I want to compare each letter in the phrase to the letter 'e' and then make it so that the count increments.

int main(void) {
  int i, x, count = 0;
  char words[] = "Yesterday, all my troubles seemed so far away", letter;
  char str1 = "e";
  for (i = 0; i < 45; i++) {
    letter = words[i];
    x = strcmp(letter, str1);
    if (x == 0) {
      count++;
    }
  }
  printf("The number of times %c appears is %d.\n", str1, count);
}

Solution

  • You can simply compare your string characters against the character 'e' like so

    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
        int i, count = 0;
        char words[] ="Yesterday, all my troubles seemed so far away";
    
        for (i = 0; i < strlen(words); i++){
            if (words[i] == 'e') {
                count++;
            }
        }
        printf("The number of times %c appears is %d.\n", 'e', count);
    }