C strstr(): Find Substring in String
In the C language, you can use the function strstr to locate the position of a substring within a string. The prototype of this function is as follows:
char *strstr(const char *haystack, const char *needle);
In this case, haystack is the string to be searched and needle is the substring to search for. The function returns the position of the first occurrence of the substring in the string, or NULL if the substring is not found.
Here is an example code:
#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("子串出现在字符串的位置:%ld\n", result - haystack);
} else {
printf("未找到子串\n");
}
return 0;
}
In the example code above, we are searching for the substring “World” in the string “Hello, World!”. If the substring is found, we will print its position in the string. If not found, we will print “Substring not found”.