How to check if string ends with .txt

后端 未结 11 1773
耶瑟儿~
耶瑟儿~ 2020-12-15 04:23

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,

相关标签:
11条回答
  • 2020-12-15 05:10

    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;
    }
    
    0 讨论(0)
  • 2020-12-15 05:12

    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

    0 讨论(0)
  • 2020-12-15 05:13

    Using boost ends_with predicate:

    #include <boost/algorithm/string/predicate.hpp>
    
    if (boost::ends_with(fileName, ".txt")) { /* ... */ }
    
    0 讨论(0)
  • 2020-12-15 05:15

    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

    0 讨论(0)
  • 2020-12-15 05:21

    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;
    }
    
    0 讨论(0)
提交回复
热议问题