How to use strstr in C

The strstr function returns a pointer to the first occurrence of string s2 in string s1. The function returns the null pointer if the string is not found. The process of matching does not include the terminating null-characters(‘\0’).

Syntax of strstr in C:

 

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

Parameters:

s1 − This is the pointer to a string to be scanned.

s2 − This is the pointer to a string containing the sequence of characters to match.

Return:

The strstr function returns a pointer to the located string, or a null pointer if the string is not found. If s2 points to a string with zero length, the function returns s1.

 

Let’s see an example code to understand the usage of the strstr in C.

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

int main()
{
    //Define a pointer of type char, a string and the substring to be found
    char *ptr;
    char s1[] = "Aticleworld.com";
    char s2[] = ".com";

    //Find memory address where s2 ",com" is found in s1
    ptr = strstr(s1, s2);

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

    //Print out return string"
    printf("%s\n", ptr);

    return 0;
}

Output:

ptr is now a pointer to the 12th letter (.) in “Aticleworld.com”.

strstr in c

 

 

Some important points related to strstr function:

1.) We must include string.h header file before using the strstr function in C.

2.) The strstr function returns a null pointer if the string is not found. Let’s see an example code,

#include <stdio.h>
#include <string.h>
int main()
{
    //Define a pointer of type char, a string and the substring to be found
    char *ptr;
    char s1[] = "Aticleworld.com";
    char s2[] = "ABC";
    
    //Find memory address where s2 "ABC" is found in s1
    ptr = strstr(s1, s2);
    if(ptr == NULL)
    {
        //Sub string not found
        printf("Sub string not found");
    }
    else
    {
        //Print out return string"
        printf("%s\n", ptr);
    }
    
    return 0;
}

Output:

Sub string not found

3.) If s2 points to a string with zero length, the function returns s1.

#include <stdio.h>
#include <string.h>
int main()
{
    //Define a pointer of type char, a string and the substring to be found
    char *ptr;
    char s1[] = "Aticleworld.com";
    char s2[] = "";

    //Find memory address where s2 "ABC" is found in s1
    ptr = strstr(s1, s2);
    if(ptr == NULL)
    {
        //Sub string not found
        printf("Sub string not found");
    }
    else
    {
        //Print out return string"
        printf("%s\n", ptr);
    }

    return 0;
}

Output:

strstr in c1 s2 zero len

 

4.) It is the programmer’s responsibility to pass the valid string in the strstr function.

 

Recommended Articles for you: