The short answer
strstr() looks for one C string inside another. It returns a pointer to the first place the search string appears, or NULL if it does not appear at all. It is declared in <string.h>.
The function signature
char *strstr(const char *haystack, const char *needle);
The first argument is the string to search, and the second is the text you are looking for. Both must be null-terminated strings. The returned pointer does not copy anything. It points into the string you searched, starting at the match.
A simple example
#include <stdio.h>
#include <string.h>
int main(void) {
const char *text = "learning C is fun";
const char *found = strstr(text, "is");
if (found != NULL) {
printf("Found: %s\n", found);
printf("Position: %ld\n", (long)(found - text));
} else {
printf("Not found\n");
}
return 0;
}
The output is:
Found: is fun
Position: 11
Subtracting the start of the string from the returned pointer gives the position of the match.
Always check for NULL
If the substring is not found, strstr returns NULL. Using that pointer without a check, for example by passing it to printf with %s, leads to undefined behavior. So compare the result with NULL first, as the example does.
What strstr does not do
- It matches anywhere in the string, not only whole words. Searching for
isalso matches inside the wordthis. - It is case-sensitive, so
ISdoes not matchis. - It does not tell you whether two strings are equal. For that, see how to compare two strings in c.
Searching text read from input
A common use is checking a line of text the user typed, such as a command. Here is a short example that reads a line with fgets and looks for the word quit:
#include <stdio.h>
#include <string.h>
int main(void) {
char line[100];
printf("Type a command: ");
if (fgets(line, sizeof(line), stdin) != NULL) {
if (strstr(line, "quit") != NULL) {
printf("Quitting...\n");
}
}
return 0;
}
Keep in mind that a line such as quitting now also contains quit, so strstr is not a whole-word check. If you need that, compare the complete word or split the line first.
The C++ equivalents
In C++, you can call the same function as std::strstr by including <cstring>. Most C++ code uses std::string instead, whose find method returns an index, or std::string::npos if nothing matches:
#include <iostream>
#include <string>
int main() {
std::string text = "learning C++ is fun";
std::string::size_type pos = text.find("is");
if (pos != std::string::npos) {
std::cout << "Found at index " << pos << "\n";
} else {
std::cout << "Not found\n";
}
return 0;
}
The output is:
Found at index 13
For more search options, see the guide to c string find.
Quick recap
strstr() finds the first occurrence of one C string inside another and returns a pointer to it, or NULL if the text is not there. Check for NULL before using the result, and remember that the match is case-sensitive and can appear in the middle of a word.