I am learning basic C++, and right now I have gotten a string from a user and I want to check if they typed the entire file name (including .txt) or not. I have the string,
Unfortunately this useful function is not in the standard library. It is easy to write.
bool has_suffix(const std::string &str, const std::string &suffix)
{
return str.size() >= suffix.size() &&
str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}
2 options I can think of beside mentioned ones:
1) regex - prob overkill for this, but simple regexes are nice and readable IMHO
2) rbegin - kind of nice, could be I am missing something, but here it is:
bool ends_with(const string& s, const string& ending)
{
return (s.size()>=ending.size()) && equal(ending.rbegin(), ending.rend(), s.rbegin());
}
http://coliru.stacked-crooked.com/a/4de3eafed3bff6e3
Using boost ends_with predicate:
#include <boost/algorithm/string/predicate.hpp>
if (boost::ends_with(fileName, ".txt")) { /* ... */ }
This should do it.
bool ends_with(const std::string & s, const std::string & suffix) {
return s.rfind(suffix) == s.length() - suffix.length();
}
Verify here
This is something that, unfortunately enough, is not present in the standard library and it's also somewhat annoying to write. This is my attempt:
bool ends_with(const std::string& str, const std::string& end) {
size_t slen = str.size(), elen = end.size();
if (slen < elen) return false;
while (elen) {
if (str[--slen] != end[--elen]) return false;
}
return true;
}