Say we have the following string:
std::string str = "The quick brown fox jumps over the lazy dog";
And we want to find "fox"
Here are three methods:
- Use
std::string::find()
- Use
boost::contains()
- Use
pystring::find()
Method 1: Use std::string::find
bool found = str.find("fox") != str.npos;
This returns an iterator pointing at the beginning of the substring if found, or std::string::npos
otherwise.
Method 2: Use boost::contains
#include <boost/algorithm/string/predicate.hpp> found = boost::contains(str, "fox");
This has the advantage of returning a boolean.
Reference: Function contains
Method 3: Use pystring::find
#include <pystring.h> found = pystring::find(str, "fox") != -1;
Reference: imageworks/pystring
Related
- How to split a string in C++
- How to do string formatting in C++
- How to replace all occurrences of a character in a std::string
- How to do case-insensitive string comparison in C++
- How to concatenate a string and an int in C++
- How to convert a string to lower or upper case in C++
- How to trim a std::string in C++
- How to get a const char* or a char* from a std::string
- How to convert an int to a std::string in C++