C Library Function - strstr()
Description
C Library Function **char *strstr(const char *haystack, const char *needle) ** searches the string haystack for the first occurrence of the string needle , excluding the terminating \0.
strstr() is a string-handling function in the C standard library, used to find the first occurrence of a substring within a string.
Declaration
Below is the declaration of the strstr() function.
char *strstr(const char *haystack, const char *needle);
The strstr() function finds the first occurrence of the substring needle in the string haystack. If found, it returns a pointer to that position; if not found, it returns NULL.
Parameters
- haystack -- The main string to search.
- needle -- The substring to find.
Return Value
Returns a pointer to the first occurrence of needle in haystack. If needle is not found in haystack, NULL is returned.
Example
The following example demonstrates the use of the strstr() function.
Example 1
#include
<
stdio.h
#include
<
string.h
int
main
(
)
{
const
char
haystack
[
20
]
=
"
RUNOOB
";
const
char
needle
[
10
]
=
"
NOOB
"
;
char
ret
;
ret
=
strstr
(
haystack
,
needle
)
;
printf
(
"
The substring is: %s
\
n
"
,
ret
)
;
return
(
0
)
;
}
Let's compile and run the above program, which will produce the following result:
子字符串是: NOOB
Example 2
#include
#include
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()The function reads fromhaystackstart searching from the beginning ofneedle, until a matching substring is found or the end ofhaystackend of the -
If both the
needleis an empty string (""),strstr()returnshaystackthe starting address of. -
strstr()is case-sensitive. For a case-insensitive search, you can usestrcasestr()(a non-standard function that may require specific library support).
Output result:
Substring found: world! This is a test string.
C Standard Library -