Check if one string is a prefix of another

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

    If you can reasonably ignore any multi-byte encodings (say, UTF-8) then you can use strncmp for this:

    // Yields true if the string 's' starts with the string 't'.
    bool startsWith( const std::string &s, const std::string &t )
    {
        return strncmp( s.c_str(), t.c_str(), t.size() ) == 0;
    }
    

    If you insist on using a fancy C++ version, you can use the std::equal algorithm (with the added benefit that your function also works for other collections, not just strings):

    // Yields true if the string 's' starts with the string 't'.
    template 
    bool startsWith( const T &s, const T &t )
    {
        return s.size() >= t.size() &&
               std::equal( t.begin(), t.end(), s.begin() );
    }
    

提交回复
热议问题