C strstr Function: Complete Guide & Examples
The function strstr is used to locate the first occurrence of one string within another string. The prototype of the function is as follows:
char *strstr(const char *haystack, const char *needle);
In this case, haystack represents the string to be searched, and needle represents the substring to search for.
Here is how to use:
#include <stdio.h>
#include <string.h>
int main() {
const char *haystack = "Hello, world!";
const char *needle = "world";
char *result = strstr(haystack, needle);
if (result) {
printf("'%s' found at position %ld\n", needle, result - haystack);
} else {
printf("'%s' not found\n", needle);
}
return 0;
}
The code above searches for the “needle” in the haystack and outputs its position if found, otherwise it outputs a message indicating it was not found.