The task for this month’s Exercise is to repeatedly call the strstr() function, locating all instances of one string (“needle”) inside another (“haystack”). Obviously your first task, which also helps with the solution, is to perform error checking on the return value from the strstr() function.
The strstr() function returns the location (pointer offset) of one string found within another. It returns NULL when the string isn’t found, which also works when you repeatedly call the function to continue searching.
My solution uses a do-while loop to find all instances in string phrase[]
of string find[]
. It also uses pointer found
to assist with the repetition:
2025_03-Exercise.c
#include <stdio.h> #include <string.h> int main() { char phrase[] = "Was this the face that launch'd a thousand ships, and burnt the topless towers of Ilium?"; char find[] = "the"; char *found; puts(phrase); found = strstr(phrase,find); if( found==NULL ) printf("String '%s' not found\n",find); else { printf("Found '%s' at offset %d.\n", find, (int)(found-phrase)); do { found = strstr(found+1,find); if( found != NULL ) printf("Found '%s' at offset %d.\n", find, (int)(found-phrase)); } while( found != NULL ); } return 0; }
The first statement to use strstr() is outside the do-while loop. This location is necessary to initialize variable found
. Further, if the function returns NULL, the string find[]
isn’t located in string phrase[]
, which means that further searching is pointless.
After the first string find[]
is located, variable found
is used inside the do-while loop to continue looking for matches. The key here is to start the search at the first character after the location stored in variable found
:
found = strstr(found+1,find);
If you forget the found+1
expression, the function repeatedly finds the same string.
Upon success, the offset is output and the loop continues until found
is equal to NULL.
Here is a sample run:
Was this the face that launch'd a thousand ships, and burnt the topless towers of Ilium?
Found 'the' at offset 9.
Found 'the' at offset 60.
And, as I wrote in the original post, if you modify string find[]
to represent only “th”, the following output is generated:
Was this the face that launch'd a thousand ships, and burnt the topless towers of Ilium?
Found 'th' at offset 4.
Found 'th' at offset 9.
Found 'th' at offset 18.
Found 'th' at offset 34.
Found 'th' at offset 60.
I hope that your solution met with success! Remember, multiple approaches are possible for any C language puzzle. Some are more elegant than others, some obfuscated, some down right ugly. If it works, you passed the challenge.