C++string去除前后空格

去除字符串的空格,C#里面直接使用trim()函数,C++里需要进行一些处理,这里介绍几种方法

一、去除前空格

方案1

string str = "  sshah hha    ";

str.erase(str.begin(), std::find_if(str.begin(), str.end(),
		std::not1(std::ptr_fun(::isspace))));
	
cout << str << endl;

方案2 

    string str = "  sshah hha    ";
    str.erase(0, str.find_first_not_of(" "));
    std::cout << str << std::endl;

二、去除后空格

方案1

string str = "  sshah hha    ";

str.erase(std::find_if(str.rbegin(), str.rend(),
	std::not1(std::ptr_fun(::isspace))).base(),str.end());

cout << str << endl;

方案2 

    string str = "  sshah hha    ";
    str.erase(str.find_last_not_of(" ") + 1);
    std::cout << str << std::endl;

 

三、去除前后空格

方案1

​

string word = "  sshah hha    ";

std::string::iterator end_pos = std::remove(word.begin(), word.end(), ' ');
word.erase(end_pos, word.end());//移除空格

cout << word << endl;

​

方案2

#include <algorithm>
#include <functional>
#include <iterator>
#include <string>


string word = "  sshah hha    ";

remove_if(word.begin(), word.end(), isspace);

cout << word << endl;

 参考:

https://www.imooc.com/wenda/detail/578420

https://bbs.csdn.net/topics/370023430

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值