Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Check if a string contains a string in C++

I have a variable of type std::string. I need to check in the event that it contains a certain std::string. How might I do that?

Is there a function that delivers valid if the string is found, and false on the off chance that it isn't?
by

2 Answers

akshay1995
Use std::string::find as follows:

if (s1.find(s2) != std::string::npos) {
std::cout << "found!" << '\n';
}

Note: "found!" will be printed if s2 is a substring of s1, both s1 and s2 are of type std::string.
RoliMishra
You can try using the find function:

string str ("There are two needles in this haystack.");
string str2 ("needle");

if (str.find(str2) != string::npos) {
//.. found.
}

Login / Signup to Answer the Question.