单词替换(北大复试上机)

前言:

21考研,不论能否进复试记录一下准备路上写下的垃圾代码。本来啃《算法笔记》,但是感觉太多了做不完,改做王道机试指南。

题目描述:

输入一个字符串,以回车结束(字符串长度<=100)。该字符串由若干个单词组成,单词之间用一个空格隔开,所有单词区分大小写。现需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。

输入描述

多组数据。每组数据输入包括3行, 第1行是包含多个单词的字符串 s, 第2行是待替换的单词a,(长度<=100) 第3行是a将被替换的单词b。(长度<=100) s, a, b 最前面和最后面都没有空格.

输出描述:

每个测试数据输出只有 1 行, 将s中所有单词a替换成b之后的字符串。

解答

#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;

}

猜你喜欢

转载自blog.csdn.net/weixin_44897291/article/details/112847604