How to use strstr in C with example

How to use strstr in C with example:

strstr method is used to find the first occurrence of a string in another string. This method stops at the terminating null character, but doesn’t consider it while matching.

This method is defined in string.h header file. It is a very useful method if you want to find one string in another string in C.

In this post, we will learn the definition of strstr and its uses.

Definition of strstr:

strstr is defined as like below:

char * strstr ( const char * firstStr, const char * secondStr );

Here,

  • firstStr is the string to scanned
  • secondStr is the string to search in firstStr.
  • It returns the pointer to the first occurrence place in firstStr of secondStr. If secondStr is not found in firstStr, it returns one null pointer.

Example program of strstr:

Let me show one example program of strstr:

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

int main()
{
    char strOne[] = "Hello World!!";
    char strTwo[] = "World";
    char strThree[] = "Universe";

    if (strstr(strOne, strTwo) != NULL)
    {
        printf("strTwo is in strOne\n");
    }
    else
    {
        printf("strTwo is not in strOne\n");
    }

    if (strstr(strOne, strThree) != NULL)
    {
        printf("strThree is in strOne\n");
    }
    else
    {
        printf("strThree is not in strOne\n");
    }
}

In this example,

  • strOne, strTwo and strThree are three strings with different values.
  • We have two if-else blocks. The first block is checking if strTwo is in strOne or not. And, the second if-else block checks if strThree is in strOne or not.

If you run the above program, it will print the below output:

strTwo is in strOne
strThree is not in strOne

strstr is useful if you want to check if a string is in another string or not. We get the pointer of the first occurrence of the word in the string. So, we can use that pointer to copy any other string to this string.

You might also like: