The return value of strstr
is the pointer to the original, unmodified, string at the point of the match. The reason why the second call displays test
is a coincidence: test
simply happens to be at the end of the searched string. Had the sBuffer
been "This is app test of strstr"
, the output for the second call would be test of strstr
, not simply test
.
To fix this, you can change your program like this:
printf("%s\n", s1 ? "This" : "");
printf("%s\n", s2 ? "test" : "");
The reason this works is that you know that the only case when strstr
would return a non-null pointer is when it finds the exact match to what you've been searching for. If all you need is a boolean "found/not found" flag, you can simply test s1
and s2
for NULL
. You are using this trick already in your final if
statement.