Find the Vowel

I admit that sometimes I need to see someone else’s code before a formerly obscure function becomes useful to me. A case in point is the strchr() function, which I rarely use.

The strchr() function scans for the first instance of a character in a string. Prototyped in the string.h header, here is the format:

char * strchr( const char s*, int c);

s is a string and c is the character. If character c is found in string s, its location (pointer) is returned, otherwise the NULL pointer is returned. This is the man page definition and it’s the way I’ve always looked at the function, which I’ve just discovered cuts the function short.

Another way to look at strchr() is that it confirms when character c exists in string s. This reverse look at the function makes it more interesting to me. I saw this approach used as a solution to a problem: How to determine whether the first character of a string is a vowel?

Here’s the function:

if( strchr("aeiouAEIOU",text[0]) )

The first character of the string is represented as text[0]. The comparison string is the collection of all vowels, both lower and upper case. If the character at the start of the string matches any character in the vowel string, a pointer is returned. It’s not saved, but the pointer itself sets the result of the if comparison to true. Otherwise the NULL pointer sets the result to false.

I had never considered using the strchr() function in this backwards manner. It presented a delicious and efficient solution to what would otherwise be a complex testing algorithm. Here’s the test code I wrote:

#include <stdio.h>
#include <string.h>

int main()
{
    char text[] = "abcdef";

    if( strchr("aeiouAEIOU",text[0] ) )
        printf("'%s' starts with a vowel\n",text);
    else
        printf("'%s' does not start with a vowel\n",text);

    return(0);
}

And the output:

'abcdef' starts with a vowel

If I modify the text[] string so that it starts with a Z, the output changes to:

'Zabcdef' does not start with a vowel

The strchr() function has a companion strrchr(), where the extra r stands for reverse. In this function, the pointer is returned for the final occurrence or character c in string s. I can’t quite think of a way to transform that function into something clever, so I’ll wait until I see someone else use it that way then steal it and post it here.

By the way, character c can be the null character, \0. When specified, the pointer returned references the null character at the end of string s.

Leave a Reply