C library function -strstr()
C Standard Library - <string.h>
Description
C Library Functionschar *strstr(const char *haystack, const char *needle) In the stringhaystackFind the first occurrence of a string inneedlethe position, not including the terminating character\0。
strstr() is a string handling function in the C standard library, used to find the first occurrence of a substring in a string.
Declaration
Below is the declaration of the strstr() function.
char *strstr(const char *haystack, const char *needle);
The strstr() function is used to find the first occurrence of the substring needle in the string haystack. If found, it returns a pointer to that location; if not found, it returns NULL.
Parameter
- haystack-- The main string to be searched.
- needle-- the substring to be searched for.
Return Value
Returns a pointer to the first occurrence of needle in haystack. If needle is not found in haystack, returns NULL.
Example
The following example demonstrates the usage of the strstr() function.
Example 1
Let us compile and run the above program, which will produce the following result:
子字符串是: NOOB
Example 2
#include <string.h>
int main() {
const char *haystack = "Hello, world! This is a test string.";
const char *needle = "world";
// Find needle in haystack
char *result = strstr(haystack, needle);
if (result != NULL) {
printf("Substring found: %s\n", result);
} else {
printf("Substring not found.\n");
}
return 0;
}
Code explanation:
strstr()function fromhaystackstart searching from the beginning ofneedle, until finding a matching substring or reachinghaystackthe end.if
needleis an empty string (""),strstr()will returnhaystackthe starting address of.strstr()is case-sensitive. If you need a case-insensitive search, you can usestrcasestr()(non-standard function, may require specific library support).
Output result:
Substring found: world! This is a test string.other extensions