通过string.find_first_not_of, string.find_last_not_of去除字符串前后的空白

本文通过示例介绍了如何使用C++标准库中的find_first_not_of()和find_last_not_of()函数来去除std::string对象的首尾空格。这两个函数帮助定位到第一个非空格字符的位置,从而实现字符串的修剪。示例代码展示了如何在实际操作中应用这两个函数。
摘要由CSDN通过智能技术生成

C++中如何去掉std::string对象的首尾空格,其中std::string所提供的find_first_not_of()和find_last_not_of()帮了个大忙,这种方法可以找寻第一个不符合条件的位置。

find_first_not_of()
语法:
  size_type find_first_not_of( const basic_string &str, size_type index = 0 );
  size_type find_first_not_of( const char *str, size_type index = 0 );
  size_type find_first_not_of( const char *str, size_type index, size_type num );
  size_type find_first_not_of( char ch, size_type index = 0 );
find_first_not_of()函数:

在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从index开始。如果没找到就返回string::nops
在字符串中查找第一个与str中的字符都不匹配的字符,返回它的位置。搜索从index开始,最多查找num个字符。如果没找到就返回

例1

/*
Filename    : StringTrim1.cpp
Compiler    : Visual C++ 8.0
Description : Demo how to trim string by find_first_not_of & find_last_not_of
*/
#include <iostream>
#include <string>

std::string& trim(std::string &);

int main() 
{
  std::string s = "   Hello World!!   ";
  std::cout << s << " size:" << s.size() << std::endl;
  std::cout << trim(s) << " size:" << trim(s).size() << std::endl;

  return 0;
}

std::string& trim(std::string &s) 
{
  if (s.empty()) 
  {
    return s;
  }

  s.erase(0,s.find_first_not_of(" "));
  s.erase(s.find_last_not_of(" ") + 1);
  return s;
}

例2

string TRIM(const string& s)
{
	string::size_type head = s.find_first_not_of(" \t\n");
	return ( string::npos == head ? "" : s.substr(head, s.find_last_not_of(" \t\n") -head + 1) );
}

例3

#include <string>

#include <iostream>
using namespace std;

int main()
{
	string strFirst ( "abced" ),strSecond("abc abc abd def");
	cout<<strFirst.find("a")<<endl;//输出结果为0,说明a当前的索引位置为0

	//函数原型:size_type find_first_not_of( Char ch, size_type index = 0 ) const;
	//返回在字符串中首次不匹配 d 的首字符索引,从2开始。
	cout<<strFirst.find_first_not_of ( "d" ,2)<<endl;	//输出结果为 2	

	cout<<strSecond.length()<<endl;//输出结果为15
	cout<<strSecond.find_first_not_of("abc",4)<<endl;	//输出结果为7
	system("pause");
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值