字符串处理中有一个非常常用的操作:删除字符串中首次出现的指定字符。对于这个操作,一般的方法是自己写函数实现,其实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.
#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;
}