我有一根绳子。如果字符串的最后一个字符是空格,我想删除它。
我尝试了以下代码,
str.erase(remove_if(str.begin(), str.end(), isspace), str.end());
但我的 g++ 编译器给了我一个错误:
error: no matching function for call to ‘remove_if(__gnu_cxx::__normal_iterator<char*,
std::basic_string<char, std::char_traits<char>, std::allocator<char> > >,
__gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>,
std::allocator<char> > >, <unresolved overloaded function type>)’
请帮忙。
第一个问题是isspace
C++ 标准库中有多个重载。最初的修复是为函数提供显式类型,以便编译器知道要获取哪个函数的地址:
#include <string>
#include <algorithm>
#include <cctype>
int main()
{
std::string str = "lol hi innit";
str.erase(std::remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end());
std::cout << str; // will output: "lolhiinnit"
}
这是一个很大的丑陋,但是,嘿,这是 C++。
其次,您的代码将删除all字符串中存在空格,这似乎不是您想要的。考虑一个关于字符串最后一个字符的简单 if 语句:
#include <string>
#include <cassert>
int main()
{
std::string str = "lol hi innit ";
assert(!str.empty());
if (*str.rbegin() == ' ')
str.resize(str.length()-1);
std::cout << "[" << str << "]"; // will output: "[lol hi innit]"
}
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)