我有一个字符串。如果它是空格,我想删除字符串的最后一个字符。 我尝试了以下代码,
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++。
其次,您的代码将删除字符串中的所有 空格,这似乎不是您想要的。考虑一个关于字符串最后一个字符的简单 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]"
}
希望这对您有所帮助。
关于c++ - 从字符串中删除一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4537930/