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.startswith(smallString);
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.startswith(smallString);
The approaches using
string::find()
orstring::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 thestd::equal
algorithm. Remember to check that the "haystack" is at least as long as the "needle".You can do this with
string::compare()
, which offers various options for comparing all or parts of two strings. This version comparessmallString
with the appropriate size prefix ofbigString
(and works correctly ifbigString
is shorter thansmallString
):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
andends_with
functions, so you will finally be able to write justbigString.starts_with(smallString)
.The simplest approach would be:
(This will also work if one of the two, or both, is a vector. Or any other standard container type.)
strstr()
returns a pointer to the first occurrence of a string within a string.I thought it makes sense to post a raw solution that doesn't use any library functions...
Adding a simple
std::tolower
we can make this case insensitive