题目用例有错误,所以下面的代码都是通不过的,不要问我为什么知道用例有误
1962: 单词替换
时间: 1 Sec 内存: 32 MB
献花: 98 解决: 50
[献花][花圈][TK题库]
题目描述
输入一个字符串,以回车结束(字符串长度<=100)。该字符串由若干个单词组成,单词之间用一个空格隔开,所有单词区分大小写。现需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。
输入
多组数据。每组数据输入包括3行,
第1行是包含多个单词的字符串 s,
第2行是待替换的单词a,(长度<=100)
第3行是a将被替换的单词b。(长度<=100)
s, a, b 最前面和最后面都没有空格。
输出
每个测试数据输出只有 1 行,
将s中所有单词a替换成b之后的字符串。
样例输入
I love Tian Qin
I
You
样例输出
You love Tian Qin
代码一
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int MaxN = 256;
int main()
{
#ifdef _DEBUG
ifstream cin("data.txt");
#endif // _DEBUG
string str, src, dst;
while (getline(cin, str))
{
getline(cin, src);
getline(cin, dst);
str = ' ' + str + ' ';
src = ' ' + src + ' ';
dst = ' ' + dst + ' ';
for (size_t pos = str.find(src); pos != std::string::npos; pos = str.find(src, pos + 1U))
{
str.replace(pos, src.size(), dst);
}
str.erase(0U, 1U);
str.erase(str.size() - 1U);
cout << str << endl;
}
#ifdef _DEBUG
cin.close();
system("pause");
#endif // _DEBUG
return 0;
}
代码二
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int MaxN = 256;
int main()
{
#ifdef _DEBUG
ifstream cin("data.txt");
#endif // _DEBUG
char data[MaxN], BeRep[MaxN], Rep[MaxN], New[MaxN], k;
while (cin.getline(data, MaxN))
{
cin.getline(BeRep, MaxN);
cin.getline(Rep, MaxN);
k = 0;
for (int i = 0; data[i] != 0; ++i)
{
int j = 0;
for (; BeRep[j] != 0 && data[i + j] != 0 && BeRep[j] == data[i + j]; ++j);
if (BeRep[j] == 0 && (data[i+j]==' ' || data[i+j] == 0) && (i == 0 || data[i - 1] == ' '))
{
for (int n = 0; Rep[n] != 0; ++n)
New[k++] = Rep[n];
i += (j-1);
}
else New[k++] = data[i];
}
New[k] = 0;
cout << New << endl;
}
#ifdef _DEBUG
cin.close();
system("pause");
#endif // _DEBUG
return 0;
}
代码三
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int MaxN = 256;
int main()
{
#ifdef _DEBUG
ifstream cin("data.txt");
#endif // _DEBUG
char data[MaxN], BeRep[MaxN], Rep[MaxN], tmp[MaxN][MaxN];
int WordN, k;
while (cin.getline(data, MaxN))
{
cin.getline(BeRep, MaxN);
cin.getline(Rep, MaxN);
WordN = 0;
k = 0;
for (int i = 0; data[i] != 0; ++i)
{
if (data[i] == ' ')
{
tmp[WordN][k] = 0;
++WordN;
k = 0;
}
else
tmp[WordN][k++] = data[i];
}
tmp[WordN][k] = 0;
if (!strcmp(tmp[0], BeRep))
cout << Rep;
else
cout << tmp[0];
for (int i = 1; i <= WordN; ++i)
{
if (!strcmp(tmp[i], BeRep))
cout << " " << Rep;
else cout << " " << tmp[i];
}
cout << endl;
}
#ifdef _DEBUG
cin.close();
system("pause");
#endif // _DEBUG
return 0;
}
因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- awee.cn 版权所有 湘ICP备2023022495号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务