我想到了几个选项,一个使用旧版 C 调用,另外两个更特定于 C++。
如果您真的拥有const char *,最好使用旧版C,但由于您的示例代码仅从std::string 创建const char *,因此我提供了其他解决方案,因为您似乎只使用字符串作为数据的 true 源。
在 C++ 中,您可以使用 string::compare 或 string::find 因此,尽管 compare 可能更有效,因为它只检查字符串的开头而不是检查任何地方并将返回值与零进行比较(find 似乎更简洁,如果您重视这一点并且速度不是最重要的,您可以改用它):
if (haystack.compare(0, needle.length(), needle) == 0)
if (haystack.find(needle) == 0)
使用遗留 C 的东西,你可以这样做:
if (strncmp (haystack.c_str(), needle.c_str(), needle.length()) == 0)
请参阅以下完整程序的示例:
#include <iostream>
#include <string>
#include <cstring>
int main (void) {
std::string haystack = "xyzzy";
std::string needle = "xy";
std::string other = "99";
if (haystack.compare(0, needle.length(), needle) == 0)
std::cout << "xy found\n";
else
std::cout << "xy not found\n";
if (haystack.compare(0, other.length(), other) == 0)
std::cout << "xx found\n";
else
std::cout << "xx not found\n";
return 0;
}
对于其他选项,只需更改上面显示的if 语句以匹配给定的示例。