I have two strings which I\'d like to compare: String
and String:
. Is there a library function that would return true when passed these two strings
If you can reasonably ignore any multi-byte encodings (say, UTF-8) then you can use strncmp for this:
// Yields true if the string 's' starts with the string 't'.
bool startsWith( const std::string &s, const std::string &t )
{
return strncmp( s.c_str(), t.c_str(), t.size() ) == 0;
}
If you insist on using a fancy C++ version, you can use the std::equal algorithm (with the added benefit that your function also works for other collections, not just strings):
// Yields true if the string 's' starts with the string 't'.
template
bool startsWith( const T &s, const T &t )
{
return s.size() >= t.size() &&
std::equal( t.begin(), t.end(), s.begin() );
}