问题 D: 单词替换 Codeup ContestID:100000580

题目链接http://codeup.cn/problem.php?cid=100000580&pid=3

题目描述
输入一个字符串,以回车结束(字符串长度<=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

代码

方法1 :

#include <iostream>
#include <string>
using namespace std;
int main() {
	string str1[101], str2, str3;
	while(cin >> str1[0]) {
		int i = 1;
		while(getchar()!='\n')
		 	cin >> str1[i++];
		cin >> str2;
		cin >> str3;
		for(int j = 0; j < i; j++) {
			if(str1[j] == str2)		
				cout << str3 << ' ';
			else					
				cout <<  str1[j] << ' ';		 	
		 }
		 cout <<endl;
	}
	return 0;
}

方法2 :

#include<stdio.h>
#include<string.h>

	int main() {
		char str1[110];
		char str2[110];
		char str3[110];
		while(gets(str1)){
			gets(str2);
			gets(str3);
			int len1 = strlen(str1),
			len2 = strlen(str2),
			len3 = strlen(str3);
			int r = 0, h = 0, i;
			char ans[110][110] = {0};

			for(i = 0; i < len1; i++) {						//存储每个单词
				if(str1[i] != ' ')
					ans[r][h++] = str1[i];
				else{
					ans[r][h] = '\0';
					r++;
					h = 0;
				}
			}
			ans[r][h]='\0';						//


			for(i = 0; i <= r; i++){						//依次比较单词
				if(!strcmp(ans[i], str2)) 
					strcpy(ans[i], str3);	
/*
				if(str2[0] == ans[i][0])
					for(h = 1; h < len2; h++){
						if(str2[h] != ans[i][h])
							continue;
					}
				if(h == len2)									
					for(h = 0; h < len3; h++)			
						ans[i][h] = str3[h];
*/	
			}
			
			for(i = 0; i <= r; i++) {						//输出
				if(i > 0)
					printf(" ");
				printf("%s", ans[i]);
			}
			printf("\n");												
		}
		return 0;		
	}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值