【字符串替换 113】

字符串替换

时间限制: 3000 ms  |  内存限制: 65535 KB
难度: 2
描述
编写一个程序实现将字符串中的所有"you"替换成"we"
输入
输入包含多行数据 

每行数据是一个字符串,长度不超过1000 
数据以EOF结束
输出
对于输入的每一行,输出替换后的字符串
样例输入
you are what you do
样例输出
we are what we do

第一次想的方法:

#include<stdio.h>
#include<string.h>
char word[1000][1000];
char s[5]="you";
char c[5]="we";
int main(){
	int x=0;
 	while(scanf("%s",word[x])!=EOF){
		if(strcmp(word[x],s)==0)
			strcpy(word[x],c);
		x++;
	}
	for(int i=0;i<x;x++)
		printf("%s",word[x]);
	printf("\n");

}

这个方法无法结束输入,EOF,目前还不知道怎么修改。

第二次AC:

#include<stdio.h>
#include<string.h>
char s[1000];
char word[1000][1000];
char s1[5]="you";
char c[5]="we";
int main(){
	while(gets(s)){
	
	memset(word,0,sizeof(word));
	int n;
	n=strlen(s);
	int	k=0,j=0;
	for(int i=0;i<n;i++){
		if(s[i]!=' '){
		word[k][j++]=s[i];
		}
		else{
			j=0;
			k++;
		}
	}

	for(j=0;j<=k;j++){
		if(strcmp(word[j],s1)==0)
			strcpy(word[j],c);
	}
	for(j=0;j<k;j++)
		printf("%s ",word[j]);
	printf("%s\n",word[k]);
	memset(s,0,sizeof(s));
	}
	
}

还是没有通过。 我只是把空格当成分词符号,像youwe这个单词中的you也需要替换。所以AC不过去。

第三次百度参考别人的:

AC通过的代码:

#include<stdio.h>
#include<string.h>
int main(){
	char a[1000];
	int i,j,n;
	while(gets(a)){
		n=strlen(a);
		for(i=0;i<n;i++)
			if(a[i]=='y' && a[i+1]=='o' && a[i+2]=='u'){
				a[i]='w';
				a[i+1]='e';
				for(j=i+2;j<n;j++)
					a[j]=a[j+1];
			}
		printf("%s\n",a);
	}
}

通过比较第i,i+1,i+2.。三个字符,如果相同则替换。别且,第i+2的后面的字符都要向前移位。

总结:理解题意,按题意做题。

不断优化,写简单易懂的代码,欢迎交流。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

paidream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值