C++ std::string Checking if a string is a prefix of another

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

C++14

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.

C++14

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();
C++17

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());
}


Got any C++ Question?