C++编程思想 第2卷 第3章 深入理解字符串 字符串的查找 查找一组字符第1次或最后一次出现的位置

本文介绍了C++中如何使用find_first_of()和find_last_of()函数来查找字符串中特定字符或字符集的首次和最后一次出现位置,同时讲解了如何在不改变原字符串的情况下,创建新的字符串对象进行操作。内容包括从头尾删除空白字符,以及在测试中的应用。
摘要由CSDN通过智能技术生成

使用find_first_of()和find_last_of()成员函数可以很方便地实现
一些小的功能,比如从字符串的头尾两端删除空白字符

不触动原字符串,而是返回一个新字符串
 

//: C03:Trim.h
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// General tool to strip spaces from both ends.
#ifndef TRIM_H
#define TRIM_H
#include <string>
#include <cstddef>

inline std::string trim(const std::string& s) {
  if(s.length() == 0)
    return s;
  std::size_t beg = s.find_first_not_of(" \a\b\f\n\r\t\v");
  std::size_t end = s.find_last_not_of(" \a\b\f\n\r\t\v");
  if(beg == std::string::npos) // No non-spaces
    return "";
  return std::string(s, beg, end - beg + 1);
}
#endif // TRIM_H //
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值