使用双指针步进即可
一个确定单词头,一个确定单词尾,然后substr切出来匹配/重组
#include<iostream> #include<string> using namespace std; void Question4_2(){//习题4.2 北京大学 单词替换 string words,search,replace; int rep = replace.size(); while(getline(cin,words)){ cin>>search>>replace; int i=0,j=0; while(i<=words.size()){ while(words[j]!=' '&&words[j]!='\0') j++;//i是首字母 j是后空格 string current = words.substr(i,j-i);//空格去掉,不+1 if(current==search){ string a = words.substr(0,i); string b = words.substr(j);//默认npos words = a+replace+b; j = a.size()+rep;//进入后空格 } i = ++j;//跳过后空格 } cout<<words<<endl; } } int main(){ Question4_2(); return 0; }