Check if one string is a prefix of another

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

    You can use this:

    for c++14 or less

    bool has_prefix
        (const std::string& str, const std::string& prefix)  {
        return str.find(prefix, 0) == 0;
    }
    

    for c++17

    //it's a little faster
    auto has_prefix
        (const std::string& str, const std::string_view& prefix) -> decltype(str.find(prefix) == 0) {
        return str.find(prefix, 0) == 0;
    }
    

提交回复
热议问题