C++单词替换 (不用任何函数,只用到str.find()找到第一个要替换单词的位置)
此方法繁琐,但思路简单。就是找到了要替换的单词的位置再逐一的将单词b拷贝到str中,若单词b的长度大于单词a,则str右移,若b<a,则str的每个字符左移,但
//情况一 当b的长度大于等于a的长度
#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
string str,a,b;
while(getline(cin,str))
{
cin>>a;
cin>>b;
int c=str.size();
int found=str.find(a);
if(found!=string::npos)
{
for(int i=found;(i-found)<b.size();++i)
{
if(i-found+1<=a.size())
str[i]=b[i-found];
else //当替换的单词大于被替换单词时整体后移
{
str.append(1,'Z');
int n=c-(found+a.size()); //从单词a的下一个单词开始是需要向后移动的,n为需要向后移动的字符个数;
int j=0;
while(n--) //从单词a以后的字符串整体向后移动一位
{
str[str.size()-1-j]=str[str.size()-2-j];
j++;
}
str[i]=b[i-found]; //前面有i++ 所以i的值已经改变了 所以while循环体用j作为循环计数;之后完全正确;
}
}
}
cout<<str<<endl;
}
}
输入
i need help
need demand
输出
i demand help