gpt4 book ai didi

C++ STD find_last_of 不工作?

转载 作者:搜寻专家 更新时间:2023-10-30 23:58:10 24 4
gpt4 key购买 nike

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

所以基本上,如果您向它传递函数 "\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;
}

返回

// s == "test 123-4    "

这是错误的。无论如何,我已经决定使用 Boost,但我仍然想知道为什么它不起作用。

谢谢。

最佳答案

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

return str.substr(first, last - first + 1);

确保您始终阅读您正在使用的功能的文档(也许直到您完全了解它为止)。

关于C++ STD find_last_of 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21527535/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com