14186: 【原4186】字符串的特殊替换
题目
题目描述
author: 程序设计思想与方法助教组张亦弛 原OJ链接:https://acm.sjtu.edu.cn/OnlineJudge-old/problem/4186 ## 问题描述
【注意】本题中, 请不要使用string.h
和cstring
等一系列C/C++包含字符串处理函数的库
编写一个程序, 分别按顺序读入以下三个内容:
1. dst
:字符串
2. sub
:字符串中被替换的子字符串
3. src
:替换的字符串
输入输出描述
输入
- 输入一个字符串
dst
, 一个被替换的子字符串sub
, 一个替换的字符串src
, 以空格分隔.dst
和src
的有效长度(不包括空白字符)不超过50,sub
的长度不超过10.
输出
- 输出替换过后的字符串
out
, 有效长度不超过150.- 若
dst
中包含sub
, 则进行一次替换,替换dst中最靠近首地址的子字符串; 将替换后的结果再进行检验, 倘若还包含sub
, 则继续进行一次替换; 替换到最终的结果没有包含sub
为止. - 若原字符串中没有被替换的字符串, 则输出
No string to replace!
. - 若替换的字符串含有被替换的子字符串, 则输出
error!
(先检验dst
是否包含sub
,再检验src
是否包含sub
).
- 若
程序运行示例1
Sample Input 1
[email protected] 163 qq
Sample Output 1
[email protected]
程序运行示例2
Sample Input 2
amtsjtuptsjtu sjtu pku
Sample Output 2
amtpkuptpku
程序运行示例3
Sample Input 3
hhhhhh hh ah
Sample Output 3
aaaaah
程序运行示例4
Sample Input 4
amtsjtuptsjtu sjtu2 pku
Sample Output 4
No string to replace!
程序运行示例5
Sample Input 5
acm.sjtu sjtu sjtu2
Sample Output 5
error!
注意
- 请不要使用
string.h
和cstring
等一系列C/C++包含字符串处理函数的库. - 不要显示多余的提示信息, 避免输出判定错误.
- 注意判断输出信息是否符合要求.
ligongzzz's solution
#include "iostream"
#include "string"
using namespace std;
int main() {
string dst, sub, src;
cin >> dst >> sub >> src;
//判断
if (dst.find(sub) == string::npos) {
cout << "No string to replace!";
return 0;
}
else if (src.find(sub) != string::npos) {
cout << "error!";
return 0;
}
//替换
while (dst.find(sub) != string::npos) {
dst.replace(dst.find(sub), sub.length(), src);
}
cout << dst;
return 0;
}