strstr() — Locate substring
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
ISO C |
both |
Format
#include <string.h>
char *strstr(const char *string1, const char *string2);
General description
Finds the first occurrence of the string pointed to by string2 (excluding the NULL character) in the string pointed to by string1.
Returned value
If successful, strstr() returns a pointer to the beginning of the first occurrence of string2 in string1.
If string2 does not appear in string1, strstr() returns NULL.
If string2 points to a string with zero length, strstr() returns string1.
Example
CELEBS51
/* CELEBS51
This example locates the string haystack in the string "needle in a
haystack".
*/
#include <stdio.h>
#include <string.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
haystack