strstr() — Locate Substring
Format
#include <string.h>
char *strstr(const char *string1, const char *string2);
Language Level
ANSI
Threadsafe
Yes
Description
The strstr()
function
finds the first occurrence of string2 in string1.
The function ignores the null character (\0) that ends string2 in
the matching process.
Return Value
The strstr()
function
returns a pointer to the beginning of the first occurrence of string2 in string1.
If string2 does not appear in string1,
the strstr()
function
returns NULL. If string2 points
to a string with zero length, the strstr()
function
returns string1.
Example
This example locates the string "haystack" in
the string "needle in a haystack".
#include <string.h>
#include <stdio.h>
int main(void)
{
char *string1 = "needle in a haystack";
char *string2 = "haystack";
char *result;
result = strstr(string1,string2);
/* Result = a pointer to "haystack" */
printf("%s\n", result);
}
/***************** Output should be similar to: *****************
haystack
*/
Related Information
- strchr() — Search for Character
- strcmp() — Compare Strings
- strcspn() — Find Offset of First Character Match
- strncmp() — Compare Strings
- strpbrk() — Find Characters in String
- strrchr() — Locate Last Occurrence of Character in String
- strspn() — Find Offset of First Non-matching Character
- wcschr() — Search for Wide Character
- wcscspn() — Find Offset of First Wide-Character Match
- wcspbrk() — Locate Wide Characters in String
- wcsrchr() — Locate Last Occurrence of Wide Character in String
- wcsspn() — Find Offset of First Non-matching Wide Character
- wcswcs() — Locate Wide-Character Substring
- <string.h>