C - String Searching for a Substring

Introduction

The strstr() function searches one string for the first occurrence of a substring and returns a pointer to the position.

If it doesn't find a match, it returns NULL.

The first argument to the function is the string that is to be searched, and the second argument is the substring you're looking for.

char text[] = "this is a test test ";
char word[] = "is";
char *pFound = NULL;
pFound = strstr(text, word);

Demo

#include <stdio.h>
#include <string.h>
int main(void)
{
  char str1[] = "this is a test test test test test.";
  char str2[] = "is";
  char str3[] = "adfd";

  // Search str1 for the occurrence of str2
  if (strstr(str1, str2))
    printf("\"%s\" was found in \"%s\"\n", str2, str1);
  else/*from   ww w  . j  ava  2  s.  c om*/
    printf("\n\"%s\" was not found.", str2);

  // Search str1 for the occurrence of str3
  if (!strstr(str1, str3))
    printf("\"%s\" was not found.\n", str3);
  else
    printf("\nWe shouldn't get to here!");
  return 0;
}

Result

Related Topics