• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2021
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools

How to Write a code to implement strstr function in C?

Aniruddha Chaudhari/56949/16
C / C++Code
YouTube CSEstack

Before implementing strstr function, first thing, you need to understand strstr function. What does strstr function do? What are its uses?

What is strstr function in C?

Strstr is the inbuilt string function given in C language. This function is used to find the substring in other string. Before to write our own code to implement the strstr function in C, I briefly introduce you an inbuilt strstr function with its syntax.

Syntax Declaration for strstr function:

int strstr(char*, char*);

This function is very easy to use in c language. It has two arguments as char strings. First string contents base string in which we want to search sub-string. The Second argument is sub-string that need to be searched in base string.

If it founds substring in the base string, it returns 1. Otherwise, it returns 0.

Now here, instead of using an inbuilt strstr function, we want to implement a strstr function in C. This function will work the same like as inbuilt strstr() function.

I have been asked this question in IBM placement interview on campus.

Code to implement strstr function in C

Complete C program to write your own strstr function.

#include<stdio.h>

int fStrStr(char* str, char* strSub)
{
	int i=0, j=0;
	int nTemp = i;
	int nStrLen = strlen(str);
	int nStrSubLen = strlen(strSub);
	for(i=0; i<nStrLen-nStrSubLen; i++)
	{
		nTemp = i;
		for(j=0; j<nStrSubLen; j++)
		{
			
			if(str[nTemp]==strSub[j])
			{
				if(j==nStrSubLen-1)
					return 1;
				nTemp++;
			}
			else 
				break;
		}
	}
	return 0;
}


int main()
{
	char str[] = "CSEStack";
	char strSub[] = "SES";

	if(fStrStr(str, strSub))
		printf("Sub-string found.");
	else
		printf("Sub-string not found.");

		
}

Output:

Case 1:

char str[] = "CSEStack";
char strSub[] = "SES";
=>Sub-string found.

Case 2:

char str[] = "CSEStack";
char strSub[] = "SDS";
=>Sub-string not found.

This is one of the top coding questions asked in an interview.

Note: Here, I am using fstrstr() function that will work as an inbuilt function strstr(). Even you can use the same function name as strstr(). If there is inbuilt as well as user-defined function with the same name, the user-defined function will get the call.

Time Complexity: O(n^2)

As in the worst case, we are comparing every letter in the base string with every letter in the substring, it’s complexity is O(n^2).

Difficulty Level: Medium

Do you have any other solution? Let’s code it in the comment section below.

Happy Programming!

c-string
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Jeevan
    June 14, 2016 at 1:20 pm

    Hi ,i found your program to be wrong
    I gave string as jeevan
    Substring as euio
    The output is
    Sbstring found only ..
    Please correct the mistake as soon as possible

    • Reply
      Aniruddha Chaudhari
      June 14, 2016 at 1:47 pm

      Hi Jeevan,

      I made the following changes as per your requirement

      char str[] = “jeevan”;
      char strSub[] = “euio”;

      The output of the program is “Sub-string not found.”

      Please check at your end at once.

  • Reply
    amna
    September 25, 2016 at 4:08 am

    HI ,i wanna also print the remaining substring how will i do?

    • Reply
      Aniruddha Chaudhari
      September 25, 2016 at 5:12 am

      Hi Amna,
      Can you give an example? what do you want to print for the both cases of matching and nonmatching string?

  • Reply
    Abhijit
    October 30, 2016 at 6:56 pm

    When i do the following
    Case 1:
    char str[] = “apple”;
    char strSub[] = “apple”;
    The output of the program is “Sub-string not found.”

    Case 2:
    char str[] = “apple”;
    char strSub[] = “apple”;
    The output of the program is “Sub-string found.”

    The program is not behaving properly when both the strings are exact match.

    • Reply
      Aniruddha Chaudhari
      November 1, 2016 at 7:26 am

      I tried running this code for exact match. I am getting correct answer. I will check for more times and if I get output as “Sub-string not found.”, will try to rectify the problem by putting some checkpoints.

      Thanks for putting your point and observation.

      • Reply
        Amrish
        July 16, 2020 at 4:22 pm

        If we give both strings are equal, due to this check “i<nStrLen-nStrSubLen" it is not entering into the logic and returning zero.

  • Reply
    Andrew Dhok
    June 4, 2017 at 6:48 pm

    I did not get any issue with this program. It is running completely fine.

    • Reply
      Aniruddha Chaudhari
      June 10, 2017 at 5:06 am

      Thanks Andrew!

  • Reply
    Amrender Pal
    September 14, 2017 at 5:26 am

    Hi, I truly appreciate your effort but I have a question.
    How can you return 1 and then do increment? Increment will never happen as you have already returned from that function (Line 17-18).

    • Reply
      Aniruddha Chaudhari
      September 15, 2017 at 5:47 pm

      Hey Hi,

      There is explicit condition “if(j==nStrSubLen-1)” for “return 1”. If thay condtion goes true, we return 1. If this condtion is false, we are incrementing nTemp variable.

      Hope this clear your doubt.

  • Reply
    srinivas
    November 14, 2017 at 10:44 am
    #include <stdio.h>
    #include <string.h>
    int usr_strstr(char *mstr, char *sstr);
    int main ()
    {
      char mstr[]="helloworld";
      char sstr[] = "world";
      char *mi = mstr;
      char *si = sstr;
      int i = 0;
      i=usr_strstr(mstr,sstr);
      if(i == 1)
      {
      	printf("string found\n");
      }
      else
      {
      	printf("string not found\n");
      }
      
    }
    int usr_strstr(char *mstr, char *sstr)
    {
    	while(*mstr != '\0')
      {
      	if(*mstr == *sstr)
      	{
      		return 1;
      		break;
    	}
    	else 
    	{
    		mstr++;
    	}
      } 
    }
  • Reply
    Venki
    December 19, 2019 at 6:41 pm

    I always thought that strstr returned a pointer (char *) and not int.

    • Reply
      Aniruddha Chaudhari
      December 20, 2019 at 8:15 am

      Yeah. It’s a bit confusing. I hope it is clear now.

  • Reply
    Aaron
    September 13, 2020 at 11:30 pm

    Hello, how or what would I have to change if I wish the function to return a char* instead of int?

    • Reply
      Aniruddha Chaudhari
      September 16, 2020 at 8:45 pm

      Here we are implementing the strstr function and it returns one if the substring found, otherwise zero. You can also return the pointer of the first occurrence of a substring in case the substring found.

Leave a Reply Cancel reply

C Programming

  1. C- Introduction
  2. C- Compile & Execute Program
  3. C- Data Types
  4. C- if-else statement
  5. C- While, do-while, for loop
  6. C- Function (Types/Call)
  7. C- strlen() vs sizeof()
  8. C- Nested Switch Statement
  9. C- Recursion
  10. C- Dynamic Programming
  11. C- Storage Classes
  12. C- Creating Header File
  13. C- Null Pointer
  14. C- Stack and Queue
  15. C- Implement Stack using Array
  16. C- Implement Linked List in C
  17. C- File Handling
  18. C- Makefile Tutorial

Object Oriented Concepts in C++

  • C++: C vs OOPs Language
  • C++: Introduction to OOPs Concepts
  • C++: Inheritance

Sorting Algorithms

  • Different Types of Sorting Algo
  • Selection Sort
  • Bubble Sort
  • Quick Sort

Programming for Practice

  1. Online C/C++ Compiler

String Handling:

  1. Remove White Spaces from String
  2. Implement strstr Function in C
  3. Convert String to Int – atoi()
  4. Check if String is Palindrome
  5. Check if Two Strings are Anagram
  6. Split String in using strtok_r()
  7. Undefined reference to strrev

Array:

  1. Check if Array is Sorted

Bit Manipulation:

  1. Count Number of 1’s in Binary

Linked List:

  1. Reverse a Linked List Elements

Number System:

  1. Program to Find 2’s Complement
  2. Convert Decimal to Binary in C

Tricky Questions:

  1. Add Two Numbers without Operator
  2. Find Next Greater Number
  3. Swap values without temp variable
  4. Print 1 to 100 without Loop

Interview Coding Questions

  • 50+ Interview Coding Questions

© 2021 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard