c/c++ trim

本文介绍了如何使用C++标准库中的`std::erase`和`std::find_if`函数来删除字符串首尾的空格。`trim_left`函数用于删除左侧空格,`trim_right`函数删除右侧空格,`trim`则同时处理两端。`std::find_if`寻找第一个非空格字符的迭代器,`std::erase`则根据该迭代器删除多余的空格。
摘要由CSDN通过智能技术生成

use erase and find_if to implement trim

c/c++ trim 实现字符串两头空格删除

#include <algorithm>
#include <cctype>
#include <locale>

inline void trim_left(std::string &str)
{
    str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](unsigned char ch) { return !std::isspace(ch); }));
}

inline void trim_right(std::string &str)
{
    str.erase(std::find_if(str.rbegin(), str.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), str.end());
}

inline void trim(std::string &str)
{
    trim_left(str);
    trim_right(str);
}

find_if:from start to end find the first element make the third func true and return the iterator

std::find_if(str.begin(), str.end(), [](unsigned char ch) { return !std::isspace(ch); })
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值