more if loops to one switch loop

I have some if cases/loops that I'd like to get rid of and find an easier (with less typing) solution. I'm guessing this kind of coding doesn't help the program speed too.

I want to calculate all the punctuation characters, all the letters, all the digits etc from a char string called 'niza'. So how do I write this better?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  for (int i=0; i<100; i++)
    {
        if (isgraph(niza[i]))
        {
            if (ispunct(niza[i]))
                punct++;
            if (isalpha(niza[i]))
            {
                let++;
                if (isupper(niza[i]))
                    up++;
                if (islower(niza[i]))
                    low++;
            }
            if (isdigit(niza[i]))
                dig++;
        }
    }

Basically I'd like to try out all the functions from http://www.cplusplus.com/reference/cctype/ in one loop.
I'm guessing a switch statement will be more efficient...But how?
Last edited on
Assuming niza is char niza[100]; , your're not terminating when you hit the \0 string termination charqacter (assuming this is a null terminated C-string).

I wouldn't bother with the isgraph() at line 3 really since you're not counting non-graphics on the assumption you're dealing with mostly graphic data. If you're truely dealing with non-graphic data, then you might skip a few instructions for non-graphic data by including it.

By the same token, I would skip the isalpha() test at line 7 since isupper() and islower() are effectively the same. If you want to know the number of letters, add up and low together at the end.

I'd put an else (or continue) after line 6 because if it's punctuation, it can't be anything else.

You might consider reordering the tests so that the most common cases are handled first, although this should be done for you by an optimizing compiler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <cctype>

int main (int argc, const char * argv[])
{   const char * ptr = argv[1];	// use command line instead of niza
    char c;
    int up = 0, low = 0, dig = 0, punct = 0, let = 0;

    while (c = *ptr++)	// While not end of string
    {   if (isupper(c))
        {	up++; continue; } 
        if (islower(c))
        {	low++; continue; } 
        if (isdigit(c))
        {	dig++; continue; } 
        if (ispunct(c))
        {	punct++; continue; } 
    }
    let = up + low;
}


edit:
BTW, the ctype tests are very efficient. In most implementations they are simply a logical and between a bitmask (test type) and a word from a table indexed by the character.

No way I can think to do this using a switch statement.
Last edited on
Topic archived. No new replies allowed.