0

I'm trying to write a function to count the number of alphanumeric character(a,b,c,d,..,z), in a string. My code looks like it doesn't have error..., but when I run it, function stops to count characters before the end of the string. Someone can find why is that? Thanks for your times.

int counter(char text[])
{
    int length = strlen(text), counter = 0;

    for (int i = 0; i < length; i++)
    {
        if (isalpha(text[i]))
        {
            counter++;
            i++;
        }
        else i++;
    }
    return counter;
}
1

Your problem is pretty simple. In a for loop, after the end of each loop, the third parameter (<increment command>) of the loop is executed, every time.

for (<initialization>; <condition>; <increment command>)

In your case your <increment command> is i++, so i gets incremented by 1 in each iteration. But, in your loop, after each iteration, you also increment i yourself. So i gets incremented by 2 in every loop instead of just 1. To solve that just remove the i++s from inside the loop. The increment command will take care of it itself.

So your function should be:

int counter(char text[])
{
    int length = strlen(text), counter = 0;

    for (int i = 0; i < length; i++)
    {
        if (isalpha(text[i]))
        {
            counter++;
        }
    }
    return counter;
}

You don't even need the else clause ;).


If this answers your question please accept it by clicking the gray check-mark to the left, so that it becomes green. You can also vote it up by pressing the up arrow above the check-mark. And don't forget to keep coding!

  • 1
    Great thanks! I have probably passed too much time watching at this code... – CharlesD89 Oct 3 '15 at 17:50
  • Good for you! It's a great course. You will learn SO much! – ChrisG Oct 3 '15 at 17:50

You must log in to answer this question.

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