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

版权声明:请勿轻易转载 https://blog.csdn.net/weixin_43838723/article/details/84677018

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.*/

猜你喜欢

转载自blog.csdn.net/weixin_43838723/article/details/84677018