14.4. strchr(), strrchr()

Find a character in a string.

Prototypes

#include <string.h>
char *strchr(char *str, int c);
char *strrchr(char *str, int c);

Description

The functions strchr() and strrchr find the first or last occurance of a letter in a string, respectively. (The extra "r" in strrchr() stands for "reverse"--it looks starting at the end of the string and working backward.) Each function returns a pointer to the char in question, or NULL if the letter isn't found in the string.

Quite straightforward.

One thing you can do if you want to find the next occurance of the letter after finding the first, is call the function again with the previous return value plus one. (Remember pointer arithmetic?) Or minus one if you're looking in reverse. Don't accidentally go off the end of the string!

Return Value

Returns a pointer to the occurance of the letter in the string, or NULL if the letter is not found.

Example

// "Hello, world!"
//       ^  ^   
//       A  B

char *str = "Hello, world!";
char *p;

p = strchr(str, ','); // p now points at position A
p = strrchr(str, 'o'); // p now points at position B
// repeatedly find all occurances of the letter 'B'
char *str = "A BIG BROWN BAT BIT BEEJ";
char *p;

for(p = strchr(str, 'B'); p != NULL; p = strchr(p + 1, 'B')) {
    printf("Found a 'B' here: %s\n", p);
}

// output is:
//
// Found a 'B' here: BIG BROWN BAT BIT BEEJ
// Found a 'B' here: BROWN BAT BIT BEEJ
// Found a 'B' here: BAT BIT BEEJ
// Found a 'B' here: BIT BEEJ
// Found a 'B' here: BEEJ

See Also