How about simply:
bool prefix(const std::string& a, const std::string& b) {
if (a.size() > b.size()) {
return a.substr(0,b.size()) == b;
}
else {
return b.substr(0,a.size()) == a;
}
}
C++ not C, safe, simple, efficient.
Tested with:
#include <string>
#include <iostream>
bool prefix(const std::string& a, const std::string& b);
int main() {
const std::string t1 = "test";
const std::string t2 = "testing";
const std::string t3 = "hello";
const std::string t4 = "hello world";
std::cout << prefix(t1,t2) << "," << prefix(t2,t1) << std::endl;
std::cout << prefix(t3,t4) << "," << prefix(t4,t3) << std::endl;
std::cout << prefix(t1,t4) << "," << prefix(t4,t1) << std::endl;
std::cout << prefix(t1,t3) << "," << prefix(t3,t1) << std::endl;
}
If you have C++17 you can write a better version of this, using std::string_view
instead:
#include <string>
#include <string_view>
bool prefix(const std::string& a, const std::string& b) {
if (a.size() > b.size()) {
return std::string_view(a.c_str(),b.size()) == b;
}
else {
return std::string_view(b.c_str(),a.size()) == a;
}
}
With g++ 7 at -O3 this collapses to a single memcmp
call, which is a fairly substantial improvement over the older version.
string.compare()
? – Parlormaidn
. – Heliopolis==
operator. ;-) – HammelN
was an unknown (while if you are looking for a prefix, it is quite well-known!) – Purifoy==
does not return true for 'String' and 'String:', "strictly" speaking or otherwise. – Chladek