简单地说:
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++ 不是 C,安全、简单、高效。
测试:
#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;
}
如果你有 C++17,你可以编写一个更好的版本,使用 std::string_view 代替:
#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;
}
}
在 -O3 处使用 g++ 7,这将折叠为单个 memcmp 调用,这比旧版本有相当大的改进。