Write an efficient program to implement strstr function in C. The strstr() function returns a pointer to the first occurrence of a string in another string.

The prototype of the strstr() is:

const char* strstr(const char* X, const char* Y);

1. Iterative Implementation

Following’s iterative implementation of the strstr() function. It returns a pointer to the first occurrence of Y in X or a null pointer if Y is not part of X. The time complexity of this solution is O(m.n) where m and n are the length of String X and Y, respectively.

Download  Run Code

Output:

Ace the Technical Interviews

2. Using memcmp() function

Following is strstr implementation using memcmp() function defined in code. The time complexity of this solution remains O(m.n).

Download  Run Code

Output:

Ace the Technical Interviews

3. Using KMP Algorithm (Efficient)

We can even use KMP Algorithm to solve this problem, which offers O(m + n) complexity, where m and n are the length of the strings X and Y, respectively.

Download  Run Code

Output:

Ace the Technical Interviews

That’s all about strstr() implementation in C.

 
Also See:

Implement strstr function in Java