Checking if a string is a prefix of another

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


std::string:
* Checking if a string is a prefix of another

Table Of Contents
8 Arrays
11 Loops
20 std::string
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype