Check if one string is a prefix of another

前端 未结 13 869
-上瘾入骨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:37

    With string::compare, you should be able to write something like:

    bool match = (0==s1.compare(0, min(s1.length(), s2.length()), s2,0,min(s1.length(),s2.length())));

    Alternatively, in case we don't want to use the length() member function:

    bool isPrefix(string const& s1, string const&s2)
    {
        const char*p = s1.c_str();
        const char*q = s2.c_str();
        while (*p&&*q)
            if (*p++!=*q++)
                return false;
        return true;
    }
    

提交回复
热议问题