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
str1.find(str2) returns 0 if entire str2 is found at the index 0 of str1:
#include
#include
// does str1 have str2 as prefix?
bool StartsWith(const std::string& str1, const std::string& str2)
{
return (str1.find(str2)) ? false : true;
}
// is one of the strings prefix of the another?
bool IsOnePrefixOfAnother(const std::string& str1, const std::string& str2)
{
return (str1.find(str2) && str2.find(str1)) ? false : true;
}
int main()
{
std::string str1("String");
std::string str2("String:");
std::string str3("OtherString");
if(StartsWith(str2, str1))
{
std::cout << "str2 starts with str1" << std::endl;
}
else
{
std::cout << "str2 does not start with str1" << std::endl;
}
if(StartsWith(str3, str1))
{
std::cout << "str3 starts with str1" << std::endl;
}
else
{
std::cout << "str3 does not start with str1" << std::endl;
}
if(IsOnePrefixOfAnother(str2, str1))
{
std::cout << "one is prefix of another" << std::endl;
}
else
{
std::cout << "one is not prefix of another" << std::endl;
}
if(IsOnePrefixOfAnother(str3, str1))
{
std::cout << "one is prefix of another" << std::endl;
}
else
{
std::cout << "one is not prefix of another" << std::endl;
}
return 0;
}
Output:
str2 starts with str1
str3 does not start with str1
one is prefix of another
one is not prefix of another