删除字符串中首次出现的指定字符

字符串处理中有一个非常常用的操作:删除字符串中首次出现的指定字符。对于这个操作,一般的方法是自己写函数实现,其实C++ string库中提供的函数就可以直接实现这个功能。需要的两个函数如下:

1、find_first_of

 #include <string>
  size_type find_first_of( const string &str, size_type index = 0 );
  size_type find_first_of( const char* str, size_type index = 0 );
  size_type find_first_of( const char* str, size_type index, size_type num );
  size_type find_first_of( char ch, size_type index = 0 );

The find_first_of() function either:

  • returns the index of the first character within the current string that matches any character in str, beginning the search at index, string::npos if nothing is found,
  • returns the index of the first character within the current string that matches any character in str, beginning the search at index and searching at most numcharacters, string::npos if nothing is found,
  • or returns the index of the first occurrence of ch in the current string, starting the search at index, string::npos if nothing is found.  
2、erase

#include <string>
  iterator erase( iterator loc );
  iterator erase( iterator start, iterator end );
  string& erase( size_type index = 0, size_type num = npos );

The erase() function either:

  • removes the character pointed to by loc, returning an iterator to the next character,
  • removes the characters between start and end (including the one at start but not the one at end), returning an iterator to the character after the last character removed,
  • or removes num characters from the current string, starting at index, and returns *this. 
通过以上两个函数的使用说明,可以写出字符串中删除指定字符的实现代码。

#include <iostream>
#include <string>
using namespace std;

int main()
{
	char ch;
	string str;
	cout << "Input the string str:" << endl;
	cin >> str;
	cout << "Input the char that you want to delete:" << endl;
	cin >> ch;
	//在字符串str中查找字符ch首次出现的位置
	//如果str中存在字符ch,返回ch的位置索引
	//如果str中不存在字符ch,返回string::npos
	string::size_type pos = str.find_first_of(ch);
	if(pos != string::npos) //字符串str中存在字符ch
	{
		str.erase(pos, 1); //从ch所在位置开始删除1个字符,亦即删除字符ch
		cout << "The string after deleted is:" << str << endl;
	}
	else //字符串str中不存在字符ch
	{
		cout << "There is no char " << ch << " in the string " << str << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值