Cocoskip
Cocoskip

Reputation: 33

Counting vowels, consonants, numbers and other symbols in a string

I'm trying to count how many vowels/consonants/numbers/other symbols there are in a string.

#include <stdio.h>
#include <string.h>
int main(void)
{
    int cons = 0, vow = 0, num = 0, oth = 0;
    int i, length;
    char str[100];

    printf("Input a string with no space : ");
    scanf("%s", &str);
    printf("=====================================\n");
    length = strlen(str);

    for(i = 0; i < length; i++)
    {
        switch(str)
        {
        case 'a': case 'e': case 'i': case 'o': case 'u': case 'y': case 'A':
        case 'E': case 'I': case 'O': case 'U': case 'Y':
            vow++;
            break;
        case 'b': case 'c': case 'd': case 'f': case 'g': case 'h': case 'j':
        case 'k': case 'l': case 'm': case 'n': case 'p': case 'q': case 'r':
        case 's': case 't': case 'v': case 'w': case 'x': case 'z':
        case 'B': case 'C': case 'D': case 'F': case 'G': case 'H': case 'J':
        case 'K': case 'L': case 'M': case 'N': case 'P': case 'Q': case 'R':
        case 'S': case 'T': case 'V': case 'W': case 'X': case 'Z':
            cons++;
            break;
        case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8:
        case 9:
            num++;
            break;
        default:
            oth++;
            break;
        }  
    } 
    printf("%s\n", str);
    printf("Number of consonants: %d\n", cons);
    printf("Number of vowels: %d\n", vow);
    printf("Number of numbers: %d\n", num);
    printf("Number of other symbols: %d\n", oth);
}

I know that my problem lacks in my 'switch' but I don't really know what to put there. Should I put something else that the name of my string?

Upvotes: 1

Views: 886

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726799

There are two common ways of accessing all characters in a C string:

  • Using an index - in your case, that would mean str[i]
  • Using a pointer - this would let you avoid strlen call.

Here is how the second approach would look:

for (char* p = str ; *p != '\0' ; p++) {
    switch (*p) {
        ...
    }
}

Note that the length and the index i are no longer necessary, because the loop will terminate when the pointer p reaches null terminator.

Also note that scanf("%s", &str); is not safe - you need to tell scanf how big is your buffer:

int numScanned = scanf("%99s", str);

This would prevent buffer overruns. Note the use of 99 for a 100-char buffer: this is done to reserve one char for null terminator character. Also note that you should not place & in front of str, because the array is already treated like a pointer when you are calling a function.

You should check numScanned to be equal to 1 to detect possible failures in scanf.

Upvotes: 2

Related Questions