单词替换(字符数组操作)

1406:单词替换


时间限制: 1000 ms         内存限制: 65536 KB
提交数: 1982     通过数: 1161 

【题目描述】

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

【输入】

第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 I

【来源】

http://ybt.ssoier.cn:8088/problem_show.php?pid=1406

 

源代码

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	char a[201];
	gets(a);
	
	char word_1[101];
	char word_2[101];
	cin>>word_1>>word_2;
	
	int len;
	int len_1;
	int len_2;
	len=strlen(a);
	len_1=strlen(word_1);
	len_2=strlen(word_2);
	
	int i;
	int j;
	
    char b[201];
	for(i=0;i<len;i++)
	     b[i]=a[i];//Copy array a to array b (too lazy to use functions)
	
	//First look up the word to replace from array a and lock its position
	for(i=0;i<len;i++)
	{
		for(j=0;j<len_1;j++)
		{
			if(toupper(a[i+j])!=toupper(word_1[j]))
			    break;//Character mismatch pop-up lookup
			    
			if(i>0&&a[i-1]!=' ')
			    break;//Not the beginning of a string and not preceded by a space is not a separate character, immediately pop up		    			    
		}
		
		//And if we complete the loop successfully we have j is equal to len_1
		if(j==len_1&&(a[i+j]==' '||i+j==len))
	    {
	    	int p;
	    	int q=0;
	    	for(p=i;p<i+j;p++)
	    	{
	    		if(q<len_2)
	    			b[p]=word_2[q];//Replace the words first
				else
				    b[p]='9';//The extra Spaces are marked with nine for easy output
				    
				q++;    
			}
		}
	}
	
	for(i=0;i<len;i++)
	     if(b[i]!='9')//No output marked 9
	         cout<<b[i];
		    
    return 0;
}

/*This method is more complex... 
But AC... Rest assured
 (the main purpose is to use character arrays rather than string arrays)...
  Novice fool around, please give me more advice.*/

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值