strchr

The strchr function checks its argument for the occurrence of a given character. If the character is found, the function returns a pointer to the location where the character occurs. The return value is a NULL pointer if the character is not found in the string.

The strchr function has two parameters. The first parameter is a pointer to the null terminated string that is being searched. The second parameter is an integer that represents the character we are looking for.

The following code shows an example of strchr in use:

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

int main()
{
        char *s = "abcdefg";
        char *r1, *r2, *r3;
        r1 = strchr(s, 'c');
        if (r1) printf("%s\n", r1);
        r2 = strchr(s, 'f');
        if (r2) printf("%s\n", r2);
        r3 = strchr(s, 'x');
        if (!r3) printf("char x was not found\n");
        return 0;
}

This code will print the following:

cdefg
fg
char x was not found
Article created on 2008-08-19 22:14:20

Post a comment