0

I don't want my code to count non-alphabetic characters. It doesn't if they are alone, or at the end of a single word string. Why does it count an extra character at the end of a multi-word string or if they are grouped together as in '1234567'? If I put in '1', it returns 0, if I put in '2', it returns 0, an so on. But if I put in '12345678', it returns 4. Why????? Ugh. Thanks in advance.

int count_letter(string text)
{
    int L = strlen(text);
    int i;

    for (i = 0; i < L; i++)
    {
        if (isalpha(text[i]))
        {
            L = L + 0;
        }
        else
        {
            L--;
        }
    }
    return L; 
1
  • I also used this code with the same results. What am I doing wrong? 'int count_letter(string text) { int L = strlen(text); int i; for (i = 0; i < L; i++) { if (islower(text[i])) { text[i] = toupper(text[i]); } if (text[i] - 'A' > 25) { L--; } else if (text[i] - 'A' < 0) { L--; } } return L; }'
    – Lperino
    Jun 22 at 17:18
0

So, the problem is a logic error in how you defined your loop. your loop is defined as for(i = 0; i < L; i++). This means that the loop will continue going until i is no longer less than L. But, in your loop, you have this bit of code: L-- that you want to execute. Each time your program/loop executes L--, you cut off one repetition of your loop and don't check one letter of your string, meaning that your loop is now i < 8, i < 7, etc. So, you are getting 4 because it is only looking at 4 of the 8 characters in 12345678.

To fix this, you will need to find a way to keep track of how many alphabetic characters there are and how long the string is in separate variables, so that the loop's iteration can be isolated from your count.

If this helps, feel free to click the check mark next to my answer to accept it. But if not, let me know and I will try to help you further.

1
  • Thank you so much. This was driving me crazy! And such an easy fix.
    – Lperino
    Jun 22 at 20:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .