how to check string start in C++

后端 未结 12 2044
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: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     
    
    using namespace std;
    
    bool startsWith(const string& haystack, const string& needle) {
        return needle.length() <= haystack.length() 
            && equal(needle.begin(), needle.end(), haystack.begin());
    }
    

提交回复
热议问题