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.startswi
The approaches using string::find() or string::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 the std::equal algorithm. Remember to check that the "haystack" is at least as long as the "needle".
#include
using namespace std;
bool startsWith(const string& haystack, const string& needle) {
return needle.length() <= haystack.length()
&& equal(needle.begin(), needle.end(), haystack.begin());
}