Check if one string is a prefix of another

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

    This is both efficient and convenient:

    str.compare(0, pre.size(), pre) == 0
    

    compare is fast because it uses the fast traits::compare method and doesn't have to copy any data.

    Here, it will compare std::min(str.size(), pre.size()) characters but if the characters in the two ranges are equal it also checks the length of pre and returns a non-zero value if pre is longer than this.

    See the documentation at cplusplus.com.

    I've written a test program that uses this code to compare prefixes and strings given on the command line.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-08 04:38
    bool IsPrefix(const std::string& prefix, const std::string& whole)
    {
      return whole.size() >= prefix.size() && whole.compare(0, prefix.size(), prefix) == 0;
    }
    
    0 讨论(0)
  • 2020-12-08 04:42

    std::string(X).find(Y) is zero if and only if Y is a prefix of X

    0 讨论(0)
  • 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 <class T>
    bool startsWith( const T &s, const T &t )
    {
        return s.size() >= t.size() &&
               std::equal( t.begin(), t.end(), s.begin() );
    }
    
    0 讨论(0)
  • 2020-12-08 04:46

    What's wrong with the "find" and checking the result for position 0 ?

    string a = "String";
    string b = "String:";
    
    if(b.find(a) == 0)
    {
    // Prefix
    
    }
    else
    {
    // No Prefix
    }
    
    0 讨论(0)
提交回复
热议问题