Skip to content

Instantly share code, notes, and snippets.

@liuml07
Last active February 1, 2019 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuml07/5672247 to your computer and use it in GitHub Desktop.
Save liuml07/5672247 to your computer and use it in GitHub Desktop.
The missing std::string::starts_with(string)
inline bool starts_with(const string &big_str, const string &small_str) {
return big_str.compare(0, small_str.length(), small_str) == 0;
}
@Liam0205
Copy link

#include <string>
namespace std {
template <typename charT>
inline bool starts_with(const basic_string<charT>& big, const basic_string<charT>& small) {
    const typename basic_string<charT>::size_type big_size = big.size();
    const typename basic_string<charT>::size_type small_size = small.size();
    const bool valid_ = (big_size >= small_size);
    const bool starts_with_ = (big.compare(0, small_size, small) == 0);
    return valid_ and starts_with_;
}

template <typename charT>
inline bool ends_with(const basic_string<charT>& big, const basic_string<charT>& small) {
    const typename basic_string<charT>::size_type big_size = big.size();
    const typename basic_string<charT>::size_type small_size = small.size();
    const bool valid_ = (big_size >= small_size);
    const bool ends_with_ = (big.compare(big_size - small_size, small_size, small) == 0);
    return valid_ and ends_with_;
}
}  // namespace std

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment