【问题标题】:How do I check if a const char* begins with a specific string? (C++)如何检查 const char* 是否以特定字符串开头? (C++)
【发布时间】:2014-12-10 06:23:36
【问题描述】:

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

例如:

string sentence = "Hello, world!";
string other = "Hello";
const char* c = sentence.c_str();

if(/*"c" begins with "other"*/)
{
    //Do something
}

如何使用 if 语句做到这一点?

【问题讨论】:

    标签: c++ string char constants


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以使用 c 函数 strstr(string1, string2) 返回指向 string1 中第一次出现的 string2 的指针。如果返回的指针指向 string1,则 string1 以您要匹配的内容开头。

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

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

      【讨论】:

        【解决方案3】:

        我想到了几个选项,一个使用旧版 C 调用,另外两个更特定于 C++。

        如果您真的拥有const char *,最好使用旧版C,但由于您的示例代码仅从std::string 创建const char *,因此我提供了其他解决方案,因为您似乎只使用字符串作为数据的 true 源。

        在 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 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 语句以匹配给定的示例。

        【讨论】:

        • 这肯定是不必要的昂贵?
        猜你喜欢
        • 2018-08-12
        • 1970-01-01
        • 2014-11-28
        • 2019-08-24
        • 2015-04-15
        • 2011-02-16
        • 2022-11-30
        • 1970-01-01
        • 2012-02-06
        相关资源
        最近更新 更多