If you want to know if a string starts with another, how would you do that in C++/STL? In Java there is String.startsWith
, Python also has string.startwith
, STL does not have a direct method for it. Instead, there are std::string::find
and std::string::compare
. Until now I used both methods, mostly depending on my current mood:
if ( str1.compare( 0, str2.length(), str2 ) == 0 )
do_something();
if ( str1.find(str2) == 0 )
do_something();
Of course, you could also do str.substr(0,str2.length()) == str2
, maybe there are still some other ways do achieve the same. find
is a bit handier than compare
, but I have seen more people recommending compare
that find
.
But which one is preferred? Is there a performance difference? Is it implementation-dependent (GCC, VC++, etc)?