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)?
The disadvantage of
findis that ifstr1is long, then it will pointlessly search all the way through it forstr2. I’ve never noticed an optimizer being smart enough to realise that you only care whether the result is 0 or not, and stop searching after the start ofstr1.The disadvantage of
compareis that you need to check thatstr2.length()is no greater thanstr1.length()(or catch the resulting exception and treat it as a false result).Disappointingly, the closest thing to what you want in the standard library is
std::strncmp(and of course you need to usec_str()with that), hence the need forboost::starts_withor your own equivalent which includes the bounds checks.