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


Question

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().

1
89
7/12/2016 5:35:54 AM

Accepted Answer

I would use compare method:

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

if (s.compare(0, t.length(), t) == 0)
{
// ok
}
161
5/31/2009 11:34:37 AM

An approach that might be more in keeping with the spirit of the Standard Library would be to define your own begins_with algorithm.

#include <algorithm>
using namespace std;


template<class TContainer>
bool begins_with(const TContainer& input, const TContainer& match)
{
    return input.size() >= match.size()
        && equal(match.begin(), match.end(), input.begin());
}

This provides a simpler interface to client code and is compatible with most Standard Library containers.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon