strstr Function

Search for the first occurrence of a string inside another string.

Include

<string.h>

Prototype

char *strstr(const char *s1, const char *s2);

Arguments

s1
pointer to the string to be searched
s2
pointer to substring to be searched for

Return Value

Returns the address of the first element that matches the substring if found; otherwise, returns a null pointer.

Remarks

This function will find the first occurrence of the string s2 (excluding the null terminator) within the string s1. If s2 points to a zero length string, s1 is returned.

Example

See the notes at the beginning of this chapter or section for information on using printf() or scanf() (and other functions reading and writing the stdin or stdout streams) in the example code.

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

int main(void)
{
  char str1[20] = "What time is it?";
  char str2[20] = "is";
  char str3[20] = "xyz";
  char *ptr;
  int res;

  printf("str1 : %s\n", str1);
  printf("str2 : %s\n", str2);
  printf("str3 : %s\n\n", str3);

  ptr = strstr(str1, str2);
if (ptr != NULL)
  {
   res = ptr - str1 + 1;
   printf("\"%s\" found at position %d\n", 
          str2, res);
  }
  else
    printf("\"%s\" not found\n", str2);
  printf("\n");

  ptr = strstr(str1, str3);
if (ptr != NULL)
  {
    res = ptr - str1 + 1;
    printf("\"%s\" found at position %d\n", 
           str3, res);
  }
  else
    printf("\"%s\" not found\n", str3);
}

Example Output

str1 : What time is it?
str2 : is
str3 : xyz

"is" found at position 11

"xyz" not found