strstr() Function in C and C++ Tutorial with Examples – POFTUT

strstr() Function in C and C++ Tutorial with Examples

C and C++ programming languages provide the strstr() function in order to find or match a string in another string. For example, we can search pof string inside the poftut.com and find matches and return the matching index number.

strstr() Function Syntax

strstr() function has the following syntax where two strings are provided as parameter. strstr() function is case sensitive which means uppercase and lower case matters. For example  pof is will not math with Pofor POF etc.

  • const char *strstr is the function that will return a pointer or handle as the char data type for the match. If there is no match it will return a null pointer.
  • const char *STR1 is the string where we will search the STR2. It is constant char pointer simply a string in C and C++.
  • const char *STR2 is the term or string which will be searched in STR2.

strstr() Function Matching Example

We will create a simple example where we will search poftut.com string or char array in the I love the poftut.com string or char array. Before starting in C and C++ string and char array are the same thing just they have a different name but under the hood, they are the same.

strstr() Function NonMatching Example

In this case, we will make an example where search terms or string do not match or found in the given string. We will search kaleinfo.com inside the string I love poftut.com web site.

This example will create an exception because the result is null and when we try to print the result it will create an error or exception.

LEARN MORE  strcmp() C Library Function Usage with Examples

Use strstr() Function For String Replacement

Another useful case for strstr() function is using it for string replacement. We can find the specified string and replace it with the given new string. We will also use the strncpy() function to replace string. We will use I love poftut.com web site and replace the poftut.com with the kaleinfo.com.

strstr() Function in PHP

With the same name and syntax, PHP programming language also provides the strstr() function. This function can be used in PHP version 5.3 and above. In the following example, we will find the user name from the email address and print to the string.

LEARN MORE  Linux tr Command Tutorial With Examples

echo '
'

Leave a Reply

Your email address will not be published. Required fields are marked *