字符串查找问题

字符串查找问题有这么几种基本情况。

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);

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容