如何检查const char*是否以特定字符串开头?(C++)

How do I check if a const char* begins with a specific string? (C++)

本文关键字:字符串 开头 C++ 何检查 检查 const char 是否      更新时间:2023-10-16

我有一个const char*变量,我想检查它是否以某个字符串开头。

例如:

string sentence = "Hello, world!";
string other = "Hello";
const char* c = sentence.c_str();
if(/*"c" begins with "other"*/)
{
    //Do something
}

如何使用if语句来完成此操作?

要检查C字符串是否以某个子字符串开头,可以使用strncmp()

对于C++字符串,有一个接受偏移量和长度的std::string::compare()重载。

您可以使用c函数strstr(string1, string2),它返回一个指向字符串1中第一个出现的字符串2的指针。如果返回的指针指向字符串1,则字符串1以您想要匹配的内容开始。

const char* str1 = "Hello World";
const char* ptr = strstr(str1, "Hello");
// -----
if(str1 == ptr)
  puts("Found");

请记住,您是其他变量,需要在strstr函数的上下文中使用它的.c_str()方法。

脑海中浮现出几个选项,一个使用遗留的C调用,另两个更特定于C++。

如果真的有一个const char *,那么最好使用遗留的C,但是,由于您的示例代码只从std::string创建了一个const char *,我提供了其他解决方案,因为您似乎只使用字符串作为真正的data源。

因此,在C++中,您可以使用string::comparestring::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 foundn";
    else
        std::cout << "xy not foundn";
    if (haystack.compare(0, other.length(), other) == 0)
        std::cout << "xx foundn";
    else
        std::cout << "xx not foundn";
    return 0;
}

对于其他选项,只需更改上面显示的if语句即可匹配给定的示例。