Check if one string is a prefix of another

前端 未结 13 897
-上瘾入骨i
-上瘾入骨i 2020-12-08 04:21

I have two strings which I\'d like to compare: String and String:. Is there a library function that would return true when passed these two strings

13条回答
  •  佛祖请我去吃肉
    2020-12-08 04:32

    str1.find(str2) returns 0 if entire str2 is found at the index 0 of str1:

    #include 
    #include 
    
    // does str1 have str2 as prefix?
    bool StartsWith(const std::string& str1, const std::string& str2)
    {   
        return (str1.find(str2)) ? false : true;
    }
    
    // is one of the strings prefix of the another?
    bool IsOnePrefixOfAnother(const std::string& str1, const std::string& str2)
    {   
        return (str1.find(str2) && str2.find(str1)) ? false : true;
    }
    
    int main()
    {
        std::string str1("String");
        std::string str2("String:");
        std::string str3("OtherString");
    
        if(StartsWith(str2, str1))
        {
            std::cout << "str2 starts with str1" << std::endl;      
        }
        else
        {
            std::cout << "str2 does not start with str1" << std::endl;
        }
    
        if(StartsWith(str3, str1))
        {
            std::cout << "str3 starts with str1" << std::endl;      
        }
        else
        {
            std::cout << "str3 does not start with str1" << std::endl;
        }
    
            if(IsOnePrefixOfAnother(str2, str1))
            {
                std::cout << "one is prefix of another" << std::endl;      
            }
            else
            {
                std::cout << "one is not prefix of another" << std::endl;
            }
    
            if(IsOnePrefixOfAnother(str3, str1))
            {
                std::cout << "one is prefix of another" << std::endl;      
            }
            else
            {
                std::cout << "one is not prefix of another" << std::endl;
            }
    
        return 0;
    }
    

    Output:

      str2 starts with str1
      str3 does not start with str1
      one is prefix of another
      one is not prefix of another
    

提交回复
热议问题