C Programming - Strings - Discussion


Which of the following function is used to find the first occurrence of a given string in another string?

[A]. strchr()
[B]. strrchr()
[C]. strstr()
[D]. strnset()

Answer: Option C


The function strstr() Finds the first occurrence of a substring in another string

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

Return Value:
On success, strstr returns a pointer to the element in s1 where s2 begins (points to s2 in s1).
On error (if s2 does not occur in s1), strstr returns null.


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

int main(void)
   char *str1 = "IndiaBIX", *str2 = "ia", *ptr;

   ptr = strstr(str1, str2);
   printf("The substring is: %s\n", ptr);
   return 0;

Output: The substring is: iaBIX

Jalal said: (Mar 10, 2012)  
Why use pointer function?

Nancy said: (Aug 23, 2012)  
How iaBIX s output what happen to india how strstr() removes india.??

Srinivas said: (May 16, 2013)  
The strstr() function finds the first occurrence of the substring in given string.

So it will return the pointer(Address) where there is matching of substring occurs.

Manisha said: (Aug 1, 2014)  
This function finds the second string matches with the first string it returns to pointer location otherwise 0.

Kd said: (Sep 12, 2015)  
How can we say that output is a BIX, because there already given strr1 = IndiaBix. How it's possible?

Nikhil said: (Nov 21, 2015)  
ia search in indiabix string from ia it will print reaming print iabix.

Ramya said: (Jun 1, 2017)  
How it prints "iabix". Can someone explain clearly?

Surbhi said: (Jan 28, 2018)  
char *strstr(const char * string, const char* substr).

It will return a pointer to the first occurrence of sub string thus will act as character array.

Arun said: (Jun 20, 2018)  
How could we solve the program without using strstr fuctions?

Rakhi Kirtankar said: (Sep 6, 2018)  
Strstr function finds one string in another string. And when it finds the second string it prints that substring along with the remaining character. And pointer is used for storing returned address

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.