Search for That String Again

It’s straightforward to use the strstr() and related C library searching functions to locate a string in a pile of text. To locate the next occurrence of that string takes a bit more work.

And the good news is that it’s not a lot more work, just some resetting of pointers.

Yes, pointers. Here is yet another situation where you must use pointers and not array notation to best accomplish a task in the C language.

The strstr() function returns a pointer referencing the location of one string found within another string. To continue searching, you need to reset the starting pointer to a position immediately after the location where the text was found. Figure 1 attempts to illustrate this concept.

Figure 1. How strstr() can be used to continue searching through a string.

Figure 1. How strstr() can be used to continue searching through a string.

Here’s some sample code for re-searching a string. It’s based on the original strstr() example from an earlier Lesson.

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

int main()
{
    char *haystack = "Was this the face that launch'd a thousand ships, And burnt the topless towers of Ilium.";
    char *needle = "the";
    char *location;

    printf("Searching:\n%s\n",haystack);
    printf("Looking for: '%s'\n",needle);

    location = strstr(haystack,needle);
    if( location == NULL)
    {
        perror("Text not found");
        return(1);
    }
    else
    {
        printf("String was found at position %d.\n",
            (int)location-(int)haystack+1);
    }

    /* reset the string starting pointer */
    haystack = location+1;
    /* search again */
    location = strstr(haystack,needle);
    if( location == NULL)
    {
        perror("String not found a second time");
        return(1);
    }
    else
    {
        printf("String was found at again position %d.\n",
            (int)location-(int)haystack+1);
    }

    return(0);
}

The key is found at Line 26, where the haystack pointer is reset to the location pointer, the address where the string was found. But, the haystack pointer needs to be one position farther in the string. At Line 26 that was accomplished by adding one to the location pointer. Then the strstr() function is used again.

Here’s the output:

Searching:
Was this the face that launch'd a thousand ships, And burnt the topless towers of Ilium.
Looking for: 'the'
String was found at position 10.
String was found at again position 51.

Ideally, this code should be set up as a loop that continues to search for matches until the search string is exhausted, i.e., the null character at the end of the string is encountered. Feel free to create such code on your own, which will save you time because such a project will be an Exercise one of these months.