如何检查字符串是否以.txt结尾

Chr*_*cle 22 c++ string

我正在学习基本的C++,现在我从用户那里得到了一个字符串,我想检查他们是否输入了整个文件名(包括.txt).我有字符串,但如何检查字符串是否以".txt"结尾?

string fileName;

cout << "Enter filename: \n";
cin >> fileName;

string txt = fileName.Right(4);
Run Code Online (Sandbox Code Playgroud)

Right(int)方法仅适用于CString,因此上述代码不起作用.如果可能的话,我想使用常规字符串.有任何想法吗?

Die*_*Epp 39

不幸的是,这个有用的功能不在标准库中.这很容易写.

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;
}
Run Code Online (Sandbox Code Playgroud)

  • @Chronicle:这是一个关于"为什么使用const"的一般性问题.`const`限定符是由编译器强制执行的promise,函数中的代码不会修改字符串.由于该函数不会修改字符串,因此您也可以做出该承诺 - 然后该函数可以传递给const字符串而无需先复制它们.如果省略const,则可能必须先复制字符串,然后才能将其传递给函数. (4认同)

ere*_*non 12

使用boost ends_with谓词:

#include <boost/algorithm/string/predicate.hpp>

if (boost::ends_with(fileName, ".txt")) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)


Jer*_*fin 11

你已经得到了不少答案,但我决定添加另一个:

bool ends_with(std::string const &a, std::string const &b) {
    auto len = b.length();
    auto pos = a.length() - len;
    if (pos < 0)
        return false;
    auto pos_a = &a[pos];
    auto pos_b = &b[0];
    while (*pos_a)
        if (*pos_a++ != *pos_b++)
            return false;
    return true;
}
Run Code Online (Sandbox Code Playgroud)

既然你得到了不少答案,那么快速测试和结果总结是值得的:

#include <iostream>
#include <string>
#include <vector>
#include <time.h>
#include <iomanip>

bool ends_with(std::string const &a, std::string const &b) {
    auto len = b.length();
    auto pos = a.length() - len;
    if (pos < 0)
        return false;
    auto pos_a = &a[pos];
    auto pos_b = &b[0];
    while (*pos_a)
        if (*pos_a++ != *pos_b++)
            return false;
    return true;
}

bool ends_with_string(std::string const& str, std::string const& what) {
    return what.size() <= str.size()
        && str.find(what, str.size() - what.size()) != str.npos;
}

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;
}

bool has_suffix2(const std::string &str, const std::string &suffix)
{
    bool index = str.find(suffix, str.size() - suffix.size());
    return (index != -1);
}

bool isEndsWith(const std::string& pstr, const std::string& substr)
{
    int tlen = pstr.length();
    int slen = substr.length();

    if (slen > tlen)
        return false;

    const char* tdta = pstr.c_str();
    const char* sdta = substr.c_str();

    while (slen)
    {
        if (tdta[tlen] != sdta[slen])
            return false;

        --slen; --tlen;
    }
    return true;
}

bool ends_with_6502(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;
}

bool ends_with_rajenpandit(std::string const &file, std::string const &suffix) {
    int pos = file.find(suffix);
    return (pos != std::string::npos);
}

template <class F>
bool test(std::string const &label, F f) {
    static const std::vector<std::pair<std::string, bool>> tests{
        { "this is some text", false },
        { "name.txt.other", false },
        { "name.txt", true }
    };
    bool result = true;

    std::cout << "Testing: " << std::left << std::setw(20) << label;
    for (auto const &s : tests)
        result &= (f(s.first, ".txt") == s.second);
    if (!result) {
        std::cout << "Failed\n";
        return false;
    }
    clock_t start = clock();
    for (int i = 0; i < 10000000; i++)
        for (auto const &s : tests)
            result &= (f(s.first, ".txt") == s.second);
    clock_t stop = clock();
    std::cout << double(stop - start) / CLOCKS_PER_SEC << " Seconds\n";
    return result;
}

int main() {
    test("Jerry Coffin", ends_with);
    test("Dietrich Epp", has_suffix);
    test("Dietmar", ends_with_string);
    test("Roman", isEndsWith);
    test("6502", ends_with_6502);
    test("rajenpandit", ends_with_rajenpandit);
}
Run Code Online (Sandbox Code Playgroud)

使用gcc的结果:

Testing: Jerry Coffin           3.416 Seconds
Testing: Dietrich Epp           3.461 Seconds
Testing: Dietmar                3.695 Seconds
Testing: Roman                  3.333 Seconds
Testing: 6502                   3.304 Seconds
Testing: rajenpandit            Failed
Run Code Online (Sandbox Code Playgroud)

VC++的结果:

Testing: Jerry Coffin           0.718 Seconds
Testing: Dietrich Epp           0.982 Seconds
Testing: Dietmar                1.087 Seconds
Testing: Roman                  0.883 Seconds
Testing: 6502                   0.927 Seconds
Testing: rajenpandit            Failed
Run Code Online (Sandbox Code Playgroud)

是的,那些是在相同的硬件上运行的,是的,我运行了很多次,并尝试使用g ++进行不同的优化选项,看看我是否能够得到它至少接近匹配VC++.我不能.我没有立即解释为什么g ++为这个测试产生了更糟糕的代码,但我相信它确实如此.


Erb*_*ica 6

使用 std::string::substr

if (filename.substr(std::max(4, filename.size())-4) == std::string(".txt")) {
    // Your code here
}
Run Code Online (Sandbox Code Playgroud)