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);
I'm surprised no one has posted this method yet:
The correct solution, as always, comes from Boost:
boost::algorithm::starts_with
.With C++20 you can use
std::basic_string::starts_with
(orstd::basic_string_view::starts_with
):To optimize a little bit:
Don't forget to
#include <cstring>
or#include <string.h>
Either create a substring that is the length of your
smallString
variable, and compare the two. Or do a search for the substringsmallString
and see if it returns index 0http://www.cplusplus.com/reference/string/string/substr/
You can use string.substr() to see any number of characters from any position, or you could use a string.find() member.