从字符串中删除字符 [英] Removing a character from a string

查看:149
本文介绍了从字符串中删除字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have a string. I want to delete the last character of the string if it is a space. i tried the following code,

str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

但是我的g ++编译器给我一个错误:

but my g++ compiler gives me an error saying:

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 ++标准库中有多个重载。初始修复是为函数提供一个显式类型,以便编译器知道哪个函数取地址:

The first problem is that isspace has multiple overloads in the C++ Standard Library. The initial fix is to provide an explicit type for the function so that the compiler knows which function to take the address of:

#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 ++。

It's a big ugly but, hey, this is C++.

其次,你的代码将删除字符串中的所有空格,这不是你想要的。考虑一个简单的if语句在字符串的最后一个字符:

Second, your code will remove all spaces in the string, which is not what you seem to want. Consider a simple if statement on the last character of the string:

#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]"
}

希望这有帮助。

这篇关于从字符串中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆