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 startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive. See also the endsWith() method.
You can use ECMAScript 6's String. prototype. startsWith() method.
Python String startswith() method returns True if a string starts with the specified prefix (string). If not, it returns False.
We can use the startsWith() method of String class to check whether a string begins with a specific string or not, it returns a boolean, true or false.
The disadvantage of find
is that if str1
is long, then it will pointlessly search all the way through it for str2
. 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 of str1
.
The disadvantage of compare
is that you need to check that str2.length()
is no greater than str1.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 use c_str()
with that), hence the need for boost::starts_with
or your own equivalent which includes the bounds checks.
boost has an algorithm starts_with
which implements it fairly efficiently: http://www.boost.org/doc/libs/1_41_0/doc/html/boost/algorithm/starts_with.html
There is no requirement regarding how STL implementations must implement find or compare, other than the standard stuff (return values ...), so it is entirely implementation dependent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With