In C++14, this is easily done by std::mismatch
which returns the first mismatching pair from two ranges:
std::string prefix = "foo";
std::string string = "foobar";
bool isPrefix = std::mismatch(prefix.begin(), prefix.end(),
string.begin(), string.end()).first == prefix.end();
Note that a range-and-a-half version of mismatch()
existed prior to C++14, but this is unsafe in the case that the second string is the shorter of the two.
We can still use the range-and-a-half version of std::mismatch()
, but we need to first check that the first string is at most as big as the second:
bool isPrefix = prefix.size() <= string.size() &&
std::mismatch(prefix.begin(), prefix.end(),
string.begin(), string.end()).first == prefix.end();
With std::string_view
, we can write the direct comparison we want without having to worry about allocation overhead or making copies:
bool isPrefix(std::string_view prefix, std::string_view full)
{
return prefix == full.substr(0, prefix.size());
}