c++ - 从字符串中删除一个字符

标签 c++ string

我有一个字符串。如果它是空格,我想删除字符串的最后一个字符。 我尝试了以下代码,

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/

相关文章:

C++ type_traits 模板,如果不是 const,则添加引用

c++ - 编译可在Mac上运行,但不能在群集上运行(Linux)

c# - 这个字符串有什么问题?

python - 将字符串的一部分更改为下标

javascript - 为什么无法在 JavaScript 中将对象属性设置为空字符串?

c++ - 如何使用 Eigen 类型库创建静态成员变量

c++ - 霍尔分区不起作用?

c++ - Q3DSurface : Semi-transparent QSurface3DSeries

c# - 以字符串形式访问对象属性并设置其值

c++ - 在 C++ 中复制字符串