输入两个字符串s1和s2,在s1 中查找s2对应的字符串是否存在,若存在则输出它第一次出现的位置;若不存在,则输出“没有找到该字符串”。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
map<int,int> p;
string str = "abcded fgeduied";//
string strstr = "ed";
size_t pos = 0;
int ncount = 0;
while(1)
{
pos=((ncount==0)?0:pos+1);//第一次pos=0,再一次则要偏移一个位置了
pos = str.find(strstr,pos);//查找ed出现位置
if(pos == string::npos)
break;
ncount++;
p.insert(pair<int, int>(ncount, pos));
}
if(ncount == 0)
{
cout<<"没有找到该字符串"<<endl;
}
else
{
map<int, int>::iterator iter;
iter = p.begin();
cout <<"字符串:"<<strstr<<endl;
cout<<"在字符串:"<<str<<"中"<<endl;
cout<< "第" << iter->first <<"次出现位置 :" << iter->second <<endl;
}
return 0;
}