C++ STD find_last_of不工作?

use*_*734 2 c++ string std

我正在尝试编写一个函数来清除前面或后面的空格中的字符串.

所以基本上,如果你传递它的功能," \tHello, this is a test! \t"那么它必须返回"Hello, this is a test!".这是我的代码,但......

string clean_str(string str)
{
    const string alphabet("abcdefghijklmnopqrstuvwxyz1234567890åäö-");

    size_t first = str.find_first_of(alphabet);
    size_t last = str.find_last_of(alphabet);
    return str.substr(first, last);
}

int _tmain(int argc, _TCHAR* argv[])
{
    string s("         test 123-4    ");
    cout << "[" << clean_str(s) << "]";
    Sleep(INFINITE);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它回来了

// s == "test 123-4    "
Run Code Online (Sandbox Code Playgroud)

哪个错了.无论如何我决定选择Boost,但我仍然想知道为什么这不起作用.

谢谢.

Jos*_*eld 6

问题是第二个参数substr- 它应该是子字符串中字符数的计数.这意味着你应该这样做:

return str.substr(first, last - first + 1);
Run Code Online (Sandbox Code Playgroud)

确保你总是阅读你正在使用的功能的文档(也许直到你明白了).