Word Substitution (Re-examination at Peking University)

Foreword:

21. Regardless of whether you can enter the retest or not, record the garbage code written on the road. I originally gnawed on "Algorithm Notes", but I felt too much to do it, so I changed it to the Kingway Computer Test Guide.

Title description:

Enter a string and end with a carriage return (string length <=100). The string consists of several words separated by a space, and all words are case sensitive. Now you need to replace one of the words with another word, and output the replaced string.

Enter description

Multiple sets of data. Each group of data input includes 3 lines, the first line is the string s containing multiple words, the second line is the word a to be replaced, (length<=100) the third line is the word b that a will be replaced. (Length<=100) s, a, b There are no spaces at the beginning and end.

Output description:

Each test data output has only 1 line, replace all words a in s with the string after b.

answer

#include<iostream>
#include<string>
using namespace std;

int main() {
    
    
	string str, pro, next;
	string spa = " ";
	getline(cin, str);
	cin >> pro >> next;
	while ((str.find(pro + spa) == 0) || (str.find(spa + pro + spa) != -1) || (str.find(spa + pro) == (str.length() - 1 - pro.length()))) {
    
    
		if (str.find(spa + pro, 0) == (str.length() - 1 - pro.length()))		//句尾
			str.replace(str.find(spa + pro), pro.length() + 1, spa + next);
		else if (str.find(pro + spa, 0) == 0)									//句首
			str.replace(str.find(pro + spa), pro.length() + 1, next + spa);
		else if (str.find(spa + pro + spa) != -1)								//句中
			str.replace(str.find(spa + pro + spa, 0), pro.length() + 2, spa + next + spa);
	}
	cout << str << endl;

}

Guess you like

Origin blog.csdn.net/weixin_44897291/article/details/112847604