C Programming/string.h/strstr

From Wikibooks, open books for an open world
Jump to navigation Jump to search

strstr is a C standard library string function as defined in string.h. strstr() has the function signature char * strstr(const char *haystack, const char *needle); which returns a pointer to a character at the first index where needle is in haystack, or NULL if not present.[1]

The strcasestr() is a function much like strstr() except that it ignores the case of both needle and haystack. strcasestr() is a non-standard function while strstr() conforms to C89 and C99.[1]


#include <stdio.h>
#include <string.h>

int main(void) 
	/* Define a pointer of type char, a string and the substring to be found*/
	char *cptr;
	char str[] = "Wikipedia, be bold";
	char substr[] = "edia, b";

	/* Find memory address where substr "edia, b" is found in str */
	cptr = strstr(str, substr);

	/* Print out the character at this memory address, i.e. 'e' */
	printf("%c\n", *cptr);

	/* Print out "edia, be bold" */
	printf("%s\n", cptr);
	return 0;

cptr is now a pointer to the sixth letter (e) in "wikipedia".

See also[edit]

  • strchr


  1. a b strcasestr(3)

External links[edit]