Find Substring into a String without Using strstr in C using Pointers

The string handling technique strstr enables the extraction of a specified string or character within the parent string (). 

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: 

Hello World

Substring:

World

The cursor advances to the first occurrence of the substring within the main string as it comes. 

Main string: 

Hello World

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

Greetings, My name is Rumi Sadaf. I work as both a content writer and a programmer. In essence, I explain what I know and aid others in understanding programming concepts. Happy Viewing.

Leave a Comment