C programming language provides the strstr()
function which is used to search a string in a string. The first occurrence of the string location is returned as a pointer location. This operation is also called searching a needle in a haystack. The search operation ends with the end of the string which consists of \0
terminating characters. The strstr() function is provided via the <string.h>
header.
strstr() Function Syntax
The syntax of the strstr() function syntax is like below. There are two parameters where the first parameter is the text we want to search the SEARCH_TERM inside it.
char *strstr(const char *STRING, const char *SEARCH_TERM)
- *STRING is the string we want to search. It is a character pointer which is also called as string type.
- *SEARCH_TERM is the term we will search in STRING.
The strstr() function returns the char pointer for the first match for the specified SEARCH_TERM. If there is no match a null pointer is returned.
Search String
We will search the string I like wisetut.com
for the search term wise
. As this string contains the search term a character pointer where the wise
start will be returned.
#include <stdio.h>
#include <string.h>
int main () {
const char str[] = "I like wisetut.com";
const char search_term[] = "wise";
char *result;
result = strstr(str, search_term);
printf("The substring is: %s\n", result);
return(0);
}
The output is like below.
The substring is: wisetut.com
Search String At The End Of Line
The strstr() function can be used to search a string at the end of the line. A string can be consist of multiple lines and the end of line characters are \n
. So in the following example, we will search the com
at the end of the line.
#include <stdio.h>
#include <string.h>
int main () {
const char str[] = "I like wisetut.com\nI like linuxtect.com\nI like pythotect.com";
const char search_term[] = "com\n";
char *result;
result = strstr(str, search_term);
printf("The substring is: %s\n", result);
return(0);
}
Check If the Specified String Exist
The strstr() function can be used to check if the specified search term exists for the specified string. If the specified SEARCH_TERM does not exist a null pointer is returned which means the SEARCH_TERM does not exist in the specified STRING. We can check the return value if it is null or not for search term existace.
#include <stdio.h>
#include <string.h>
int main () {
const char str[] = "I like wisetut.com\nI like linuxtect.com\nI like pythotect.com";
const char search_term[] = "commm\n";
char *result;
result = strstr(str, search_term);
if(result){
printf("The substring is: %s\n", result);
}else{
printf("The specified search term does not exist");
}
return(0);
}