Search code examples
cstringstrchr

Detect vowels in a string


Im trying to write a function that detects vowels and digits in a string. iterating through the string, im trying to do a one-line if statement to check if a character is a vowel. Code as below...

void checkString(char *str)
{
    char myVowels[] = "AEIOUaeiou";

    while(*str != '\0')
    {
        if(isdigit(*str))
            printf("Digit here");
        if(strchr(myVowels,*str))
            printf("vowel here");
        str++;
    }
}

The digit checking works perfectly. However "(strchr(myVowels,*str))" doesnt work. It says different types for formal and actual parameter 1. Can anyone help me here? Thanks


Solution

  • Most likely you haven't included proper header files.

    This works just fine:

    #include <stdio.h>
    #include <ctype.h>
    #include <string.h>
    
    void checkString(const char *str)
    {
        char myVowels[] = "AEIOUaeiou";
    
        printf("checking %s... ", str);
    
        while(*str != '\0')
        {
            if(isdigit(*str))
                printf("Digit here ");
            if(strchr(myVowels,*str))
                printf("vowel here ");
            str++;
        }
    
        printf("\n");
    }
    
    int main(void)
    {
      checkString("");
      checkString("bcd");
      checkString("123");
      checkString("by");
      checkString("aye");
      checkString("H2CO3");
      return 0;
    }
    

    Output (ideone):

    checking ... 
    checking bcd... 
    checking 123... Digit here Digit here Digit here 
    checking by... 
    checking aye... vowel here vowel here 
    checking H2CO3... Digit here vowel here Digit here