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'm surprised no one has posted this method yet:
#include <string>
using namespace std;
bool starts_with(const string& smaller_string, const string& bigger_string)
{
return (smaller_string == bigger_string.substr(0,smaller_string.length()));
}
To optimize a little bit:
if ( smallString.size() <= bigString.size() &&
strncmp( smallString.c_str(), bigString.c_str(), smallString.length() ) == 0 )
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 substring smallString
and see if it returns index 0
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...
// 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;
}
The simplest approach would be:
if ( smallString.size() <= bigString.size()
&& std::equals( smallString.begin(), smallString.end(), bigString.end() )
(This will also work if one of the two, or both, is a vector. Or any other standard container type.)