The string handling technique strstr enables the extraction of a specified string or character within the parent string ().
Table of Contents
What is strstr function in c?
The function strstr is defined in the string.h header file of the C programming language. A pointer referring to the initial character of a matched string is returned. The result is null if the required string cannot be found.
Also Read: How to compare two strings without using Strcmp in C?
Syntax: strstr(const char *string1, const char *string2);
string1: The string that will be detected or where string2 will be found.
string2: the string within string1 that has to be looked up.
This function takes twos string as an argument and searches for string1’s first appearance in string2. The detection algorithm disregards the null character after string 2. However, strstr() does not regard a single letter in either uppercase or lowercase as a different character.
Also Read: How to Change string to upper case without Strupr in C?
How Does it work?
Firstly, we establish two variables—the core string and the substring—to search for the string.
Main string:
H | e | l | l | o | W | o | r | l | d |
Substring:
W | o | r | l | d |
The cursor advances to the first occurrence of the substring within the main string as it comes.
Main string:
H | e | l | l | o | W | o | r | l | d |
For locating a single string within a lengthy paragraph, use this technique.
Find Substring into a String Using Strstr Function in C.
#include <stdio.h>
#include <string.h>
//Header file for basic i/o and string handling functions
int main ()
//Entry point of the program to execute
{
const char string1[20] = “Hello World”;
const char string2[10] = “World”;
char *res;
//Declare const char variable and a pointer
res = strstr(string1, string2);
//Returns pointer pointing to string2 within string1
printf(“%s\n”, res);
Print result
return(0);
}
Output: World
Find Substring into a String without Using strstr in C using Pointers.
#include <string.h>
#include <stdio.h>
//Header file for basic i/o and string handling functions
int main()
//Entry point of the program to execute
{
const char *string1 = “Hello World”;
const char *string2 = “World”;
char *result;
//Declaring a pointer
result = strstr(string1,string2);
//Returns pointer pointing to string2 within string1
printf(“%s\n”, result);
}
Output: World