单词替换

cuosumei608 2017-06-10 01:52:32
题目描述:
输入一个字符串,以回车结束(字符串长度<=100)。该字符串由若干个单词组成,单词之间用一个空格隔开,所有单词区分大小写。现需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。
输入:
多组数据。每组数据输入包括3行,
第1行是包含多个单词的字符串 s,
第2行是待替换的单词a,(长度<=100)
第3行是a将被替换的单词b。(长度<=100)
s, a, b 最前面和最后面都没有空格.
输出:
每个测试数据输出只有 1 行,
将s中所有单词a替换成b之后的字符串。
样例输入:
You want someone to help you
You
I
样例输出:
I want someone to help you

下面是程序,在本地运行没错,但是每次提交都说是Wrong Answer,
麻烦各位给看一下,感激不尽
#include <iostream>
#include <stdio.h>
#include <string>
#include <ctype.h>
using namespace std;

int main() {
char stra[201];
while(gets(stra)){
string a = stra;
char strb[201];
char strc[201];
gets(strb); gets(strc);
string b = strb; string c = strc;
int startpos = 0;
int pos = a.find(b, startpos);
while(pos != string::npos) {
a.erase(pos, b.size());
a.insert(pos, c);
startpos = pos + c.size();
pos = a.find(b, startpos);
}
cout << a << endl;
}

return 0;

}
...全文
402 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2017-06-12
  • 打赏
  • 举报
回复
代码功能归根结底不是别人帮自己看或讲解或注释出来的;而是被自己静下心来花足够长的时间和精力亲自动手单步或设断点或对执行到某步获得的中间结果显示或写到日志文件中一步一步分析出来的。 提醒:再牛×的老师也无法代替学生自己领悟和上厕所! 单步调试和设断点调试(VS IDE中编译连接通过以后,按F10或F11键单步执行,按Shift+F11退出当前函数;在某行按F9设断点后按F5执行停在该断点处。)是程序员必须掌握的技能之一。
cuosumei608 2017-06-10
  • 打赏
  • 举报
回复
明白了, 表示已经是最后一个单词了
cuosumei608 2017-06-10
  • 打赏
  • 举报
回复
解决了,但是没明白为什么:
#include <iostream>
#include <stdio.h>
#include <string>
#include <ctype.h>
using namespace std;

int main()	{
	char stra[201];
	while(gets(stra)){
		string a = stra;
		char strb[201];
		char strc[201];
		gets(strb); gets(strc);
		string b = strb;	string c = strc;
		int pos = a.find(b, 0);
		while(pos != string::npos)	{
			if ((a[pos-1] == ' ' || pos == 0) && (a[pos + b.size()] == ' ') || a[pos + b.size()] == 0){			
				a.erase(pos, b.size());
				a.insert(pos, c);
				pos = a.find(b, pos);
			}
			else{
				pos = a.find(b, pos + b.size());
			}
		}
		cout << a << endl;
	}

	return 0;

}
if ((a[pos-1] == ' ' || pos == 0) && (a[pos + b.size()] == ' ') || a[pos + b.size()] == 0){ 这一行没明白最后等于0的意义 有人能指点一下吗?

33,321

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧