Search code examples
cfor-loopcountcs50c-strings

creating a count_letters function in c?


Task: Create a C code that gets some text input from the user and prints out a count of the number of letters in it. Letters can be any uppercase or lowercase alphabetic characters, but shouldn’t include any punctuation, digits, or other symbols.

  • I have written this code but it prints the wrong output ( for example if input is "Ad" the output is "1 letter(s)" !) and I can't find the bug in it! Thanks!
#include <stdio.h>
#include <ctype.h>
#include <cs50.h>
#include <string.h>

int main (void)
{
    char alphabets[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    string text = get_string("Text: ");
    int length = strlen(text);
    int n = 0;
    for (int i = 0; i < length; i++)
    {
        for (int j = 0; j < length; j++)
        {
            if (alphabets[j] == text[i] || toupper(alphabets[j]) == text[i])
            {
                m++;
            }
        }
        if (m == 0)
        {
            length--;
        }
        m = 0;
    }
    printf ("%i letter(s) \n", length);
    
}

Solution

  • You should use isalpha

    Then you can simply do:

    int main (void)
    {
        string text = get_string("Text: ");
        size_t length = strlen(text);
        int n = 0;
        for (size_t i = 0; i < length; ++i)
        {
            if (isalpha(text[i])) ++n;
        }
        printf ("%i letter(s) \n", n);   
    }