[Ybtoj Chapter 6 Example 3] Word replacement [string]

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here


Problem solving ideas

It is still string violence. .
Note that all words a in the sentence must become word b, and there is more than one! !


Code

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <cmath>
using namespace std;

int k=0,h,t;
string s,a,b;
 
int main(){
    
    
	getline(cin,s);
	cin>>a>>b;
	for(int i=0;i<s.size();i++)
	{
    
    
		if(s[i]==a[k])
		{
    
    
			if(k==a.size()-1)
			{
    
    
				h=i-a.size()+1;
				s.replace(h,a.size(),b);
				i=i-a.size()+b.size();
			}				
			k++;
		}
		else k=0;
	}
	cout<<s;
} 

Guess you like

Origin blog.csdn.net/kejin2019/article/details/113141830