Share this page

# strstr

String Manipulation Functions

Returns the first occurrence of one string in another.

    char *strstr( const char *string1, const char *string2);

string1 | The string that is searched.
string2 | The string that is searched for in the first string.

## Return Values

Returns a pointer to the first occurrence of string2 in string1. If string2 is not found in string1 the function returns NULL.

## Example

## Example 1

This example uses strstr to search for the word "dog" in the string, str.

After strstr returns the address, position, the code then calculates the word's place in str by subtracting the address of the start of the string from position. This is the offset of the word "dog", in bytes.

        #include <string.h>

        int offset;
        char * position;
        char * str = "The quick brown dog jumps over the lazy fox";
        char * search_str = "dog";
        position = (char *)strstr(str, search_str);

        // strstr has returned the address. Now calculate * the offset from the beginning of str

        offset = (int)(position - str + 1);
        lr_output_message ("The string \"%s\" was found at position %d", search_str, offset);

    Example: Output:
    Action.c(14): The string "dog" was found at position 17

## Example 2

The next example shows how strstr can be used to parse file name suffixes. The code checks the equality of the following two pointers:

- The pointer returned by strstr after searching for the substring is either null on failure, or the address of the first character of the file suffix on success. Adding 4 moves the pointer to the end of the string.

- The start of the string (path) plus its length, len. This is also the end of the string.

If these 2 pointers are equal than strstr has found the file suffix. If not, strstr has returned null.

        #include <string.h>

        char * path = "c:\\tmp\\xxx\\foo.ocx";
        int len = strlen(path), filetype;

        // Check the suffix of the file name to determine its type

        if ((char *)(strstr(path, ".dll") + 4) == (path + len))
            filetype = 1;
        else if ((char *)(strstr(path, ".exe") + 4) == (path + len))
            filetype = 2;
        else if ((char *)(strstr(path, ".tlb") + 4) == (path + len))
            filetype = 3;
        else if ((char *)(strstr(path, ".ocx") + 4) == (path + len))
            filetype = 4;
        else
            filetype = 5;

        lr_output_message ("type = %d", filetype);

    Example: Output:
    Action.c(18): type = 4

Tips to improve your search results... VuGen Function Reference Version 26.1 Function Reference 26.1 All View Local Help Center View Online Help Center Version: