1
0
Fork 0

Implement starts_with and ends_with functions

There are many options for implementing these functions; using C++14
std::equals is the simplest one, and allows for marking the function as
noexcept.
This commit is contained in:
Patryk Obara 2020-05-09 21:47:21 +02:00 committed by Patryk Obara
parent 064108c9c4
commit f49eb0904b
2 changed files with 18 additions and 4 deletions

View file

@ -155,9 +155,7 @@ void upcase(std::string &str);
void lowcase(std::string &str);
void strip_punctuation(std::string &str);
template<size_t N>
bool starts_with(const char (& pfx)[N], const std::string &str) noexcept {
return (strncmp(pfx, str.c_str(), N) == 0);
}
bool starts_with(const std::string &prefix, const std::string &str) noexcept;
bool ends_with(const std::string &suffix, const std::string &str) noexcept;
#endif

View file

@ -64,6 +64,22 @@ void lowcase(std::string &str) {
std::transform(str.begin(), str.end(), str.begin(), tf);
}
bool starts_with(const std::string &prefix, const std::string &str) noexcept
{
const size_t n = prefix.length();
const auto pfx = std::cbegin(prefix);
const auto txt = std::cbegin(str);
return std::equal(pfx, pfx + n, txt, txt + n);
}
bool ends_with(const std::string &suffix, const std::string &str) noexcept
{
const size_t n = suffix.length();
const auto sfx = std::crbegin(suffix);
const auto txt = std::crbegin(str);
return std::equal(sfx, sfx + n, txt, txt + n);
}
void trim(std::string &str) {
std::string::size_type loc = str.find_first_not_of(" \r\t\f\n");
if (loc != std::string::npos) str.erase(0,loc);