The strstr function checks if a string given as input appears as a substing of another. This function is similar to strchr, however, instead of looking for the occurrence of a specific character inside the target string, the strstr function tries to find a match for another substring as part of the original string. If a matching is found, the function returns a pointer to the location where the substring occurs. The return value is a NULL pointer if the substring is not matched.

The strstr function has two parameters. The first parameter is a pointer to the null terminated string that represents the pattern we want to search. The second parameter is the string where we want to search for the occurrence of the pattern given in the first parameter.

The following code shows an example of strstr in use:

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

int main()
        char *s = "abcdefg";
        char *r1, *r2, *r3;
        r1 = strchr(s, "ab");
        if (r1) printf("%s\n", r1);
        r2 = strchr(s, "def");
        if (r2) printf("%s\n", r2);
        r3 = strchr(s, "xy");
        if (!r3) printf("string xy was not found\n");
        return 0;

This code will print the following result:

string xy was not found
Article created on 2008-08-19 22:21:45

Post a comment