how to check string start in C++

后端 未结 12 2001
Happy的楠姐
Happy的楠姐 2020-11-29 03:31

Is there any way in C++ to check whether a string starts with a certain string (smaller than the original) ? Just like we can do in Java

bigString.startswi         


        
相关标签:
12条回答
  • 2020-11-29 04:22

    The correct solution, as always, comes from Boost: boost::algorithm::starts_with.

    0 讨论(0)
  • 2020-11-29 04:23

    The approaches using string::find() or string::substr() are not optimal since they either make a copy of your string, or search for more than matches at the beginning of the string. It might not be an issue in your case, but if it is you could use the std::equal algorithm. Remember to check that the "haystack" is at least as long as the "needle".

    #include <string>    
    
    using namespace std;
    
    bool startsWith(const string& haystack, const string& needle) {
        return needle.length() <= haystack.length() 
            && equal(needle.begin(), needle.end(), haystack.begin());
    }
    
    0 讨论(0)
  • 2020-11-29 04:29
    std::string s("Hello world");
    
    if (s.find("Hello") == 0)
    {
        std::cout << "String starts with Hello\n";
    }
    
    0 讨论(0)
  • 2020-11-29 04:33

    You can do this with string::compare(), which offers various options for comparing all or parts of two strings. This version compares smallString with the appropriate size prefix of bigString (and works correctly if bigString is shorter than smallString):

    bigString.compare(0, smallString.length(), smallString) == 0
    

    I tend to wrap this up in a free function called startsWith(), since otherwise it can look a bit mysterious.

    UPDATE: C++20 is adding new starts_with and ends_with functions, so you will finally be able to write just bigString.starts_with(smallString).

    0 讨论(0)
  • 2020-11-29 04:35

    With C++20 you can use std::basic_string::starts_with (or std::basic_string_view::starts_with):

    #include <string_view>
    
    std::string_view bigString_v("Winter is gone"); // std::string_view avoids the copy in substr below.
    std::string_view smallString_v("Winter");
    if (bigString_v.starts_with(smallString_v))
    {
        std::cout << "Westeros" << bigString_v.substr(smallString_v.size());
    }
    
    0 讨论(0)
  • 2020-11-29 04:38

    http://www.cplusplus.com/reference/string/string/substr/

    You can use string.substr() to see any number of characters from any position, or you could use a string.find() member.

    0 讨论(0)
提交回复
热议问题