字符串查找问题
字符串查找问题有这么几种基本情况。
1.查找子串第一次出现的位置(find(string))
string::size_type pos;//标识字符串的某个位置
string str = "this is an test of an string searching";//测试字符串
string anstr = "an";//测试子字符串
pos = str.find(anstr);
if(pos!=string::npos)//第一次查找到子串
{
cout<<"first find at position"<<pos<<endl;
}
2.查找子串最后一次出现的位置(rfind(string))
pos = str.rfind(anstr);//最后一次查找到子串
if(pos!=string::npos)
{
cout<<"last find at position:"<<pos<<endl;
}
3.查找子串所有出现的位置(find+while循环)
string::size_type pos;
string str("this is a string of test a multi ocurance of some substring,you can try to find some bugs of it.");
string astr = "a";
string ofstr = "of";
string somestr = "some";
pos = str.find(ofstr);
while(pos != string::npos)
{
cout<<"find 'of' at position:"<<pos<<endl;
pos = str.find(ofstr, pos+1);//重复查找子串of出现的位置
}
4.查找子串所有出现的位置,并且替换子串为其他子串(find+while循环+replace)
pos = str.find(astr);
while(pos != string::npos)
{
str.replace(pos, 1, "A");//替换从pos开始的1个字符为A
pos = str.find(astr);
}
cout<<str<<endl;
5.查找子串所有出现的位置,并且删除子串(find+while循环+erase)
pos = str.find(somestr);
while(pos != string::npos)
{
str.erase(pos, 5);//删除从pos开始的5个字符
pos = str.find(somestr);
}