How to use strstr in C with example:
strstr method is used to find the first occurrence of a string in another string. This method stops at the terminating null character, but doesn’t consider it while matching.
This method is defined in string.h header file. It is a very useful method if you want to find one string in another string in C.
In this post, we will learn the definition of strstr and its uses.
Definition of strstr:
strstr is defined as like below:
char * strstr ( const char * firstStr, const char * secondStr );
Here,
- firstStr is the string to scanned
- secondStr is the string to search in firstStr.
- It returns the pointer to the first occurrence place in firstStr of secondStr. If secondStr is not found in firstStr, it returns one null pointer.
Example program of strstr:
Let me show one example program of strstr:
#include <stdio.h>
#include <string.h>
int main()
{
char strOne[] = "Hello World!!";
char strTwo[] = "World";
char strThree[] = "Universe";
if (strstr(strOne, strTwo) != NULL)
{
printf("strTwo is in strOne\n");
}
else
{
printf("strTwo is not in strOne\n");
}
if (strstr(strOne, strThree) != NULL)
{
printf("strThree is in strOne\n");
}
else
{
printf("strThree is not in strOne\n");
}
}
In this example,
- strOne, strTwo and strThree are three strings with different values.
- We have two if-else blocks. The first block is checking if strTwo is in strOne or not. And, the second if-else block checks if strThree is in strOne or not.
If you run the above program, it will print the below output:
strTwo is in strOne
strThree is not in strOne
strstr is useful if you want to check if a string is in another string or not. We get the pointer of the first occurrence of the word in the string. So, we can use that pointer to copy any other string to this string.
You might also like:
- C program to print a name multiple times without using loop or function
- What is compilation and how compilation process works in C
- C program to check if a string is empty or not
- How to find the LCM of two numbers in C
- C program to check if a character is uppercase without using a library function
- fork() method explanation with example in C
- C program to reverse a string without using any library function(strrev)