std::string comparison (check whether string begins with another string)

jackhab picture jackhab · May 31, 2009 · Viewed 67.2k times · Source

I need to check whether an std:string begins with "xyz". How do I do it without searching through the whole string or creating temporary strings with substr().

Answer

Wacek picture Wacek · May 31, 2009

I would use compare method:

std::string s("xyzblahblah");
std::string t("xyz")

if (s.compare(0, t.length(), t) == 0)
{
// ok
}