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
I thought it makes sense to post a raw solution that doesn't use any library functions...
// Checks whether `str' starts with `start'
bool startsWith(const std::string& str, const std::string& start) {
if (&start == &str) return true; // str and start are the same string
if (start.length() > str.length()) return false;
for (size_t i = 0; i < start.length(); ++i) {
if (start[i] != str[i]) return false;
}
return true;
}
Adding a simple std::tolower
we can make this case insensitive
// Checks whether `str' starts with `start' ignoring case
bool startsWithIgnoreCase(const std::string& str, const std::string& start) {
if (&start == &str) return true; // str and start are the same string
if (start.length() > str.length()) return false;
for (size_t i = 0; i < start.length(); ++i) {
if (std::tolower(start[i]) != std::tolower(str[i])) return false;
}
return true;
}