C program to implement own strstr() function

Here, we are going to learn how to implement own strstr() function in C programming language?
Submitted by Nidhi, on July 21, 2021

Problem Solution:

Here, we will implement a user-defined function to perform a similar operation to the strstr() function. The strstr() function is used to find the first occurrence of a specified substring within the string and returns the pointer to the calling function. It returns NULL if the substring is not found within the string.

Program:

The source code to implement own strstr() function is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to implement own strstr() function

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

char* StrStr(char* str, char* substr)
{
    static char* ptr;

    ptr = str;

    while (*ptr) {
        if (strncmp(ptr, substr, strlen(substr)) == 0)
            return ptr;
        ptr++;
    }
    return NULL;
}

int main()
{
    char str[32] = "India is great country";
    char* ptr;

    ptr = StrStr(str, "great");
    if (ptr != NULL)
        printf("String is: '%s'\n", ptr);
    else
        printf("Word 'great' is not found\n");

    ptr = StrStr(str, "power");
    if (ptr != NULL)
        printf("String is: %s\n", ptr);
    else
        printf("Word 'power' is not found\n");

    return 0;
}

Output:

String is: 'great country'
Word 'power' is not found

Explanation:

In the above program, we created two functions StrStr() and  main(). The StrStr() is a user-defined function, which is used to find the first occurrence of a specified substring within the string and returns the pointer to the calling function. It returns NULL if the substring is not found within the string.

In the main() function, we created a string str initialized with "India is great country". Then we called StrStr() function to find the specified substring "great" within the string and print the result on the console screen.

C String Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.