dimanche 29 mars 2020

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

Aucun commentaire:

Enregistrer un commentaire