题目描述
编写一个程序实现将字符串中的所有"you"替换成"we"
输入
输入包含多行数据 ,以EOF结束
每行数据是一个字符串,长度不超过1000
输出
对于输入的每一行,输出替换后的字符串
样例输入
you are what you do
样例输出
we are what we do
思路
程序的要求是将字符串中的所有"you"替换成"we",并且输入包含多行数据 ,以EOF结束,每行数据是一个字符串,长度不超过1000。
因此我们可以用char str1[1000]来存储每行的字符串,用char str2[1000]来存储替换后的字符串,用while (gets(str))来逐行读入,接下来三个三个的进行判断,将所有的you替换为we。
注意字符串中的所有you不是特指这个单词,而是字符串中出现的子串,比如kkyour are what需要改为kkwer are what。
代码详细过程:
逐行读取输入: 使用 gets 函数逐行读取输入的字符串。
遍历字符串: 对于每一行输入的字符串,通过 for 循环遍历其中每个字符。
检查 "you": 在循环中,通过条件判断检查当前字符及后两个字符是否构成 "you"。如果是,则在str2中存入 "we" 并将循环变量 i 向前移动两个位置(因为for循环本身有i++,所以此处是+2),以跳过 "you"。
输出处理后的字符串,然后 while 循环,继续处理下一行字符串。
错误代码
读入数据到了str1数组,后面却对str2数组操作。这个思路是对的,应该将后面的str2改成str1。
#include <stdio.h>
#include <string.h>
int main()
{
char str1[1000], str2[1000], c;
while (fgets(str1, sizeof(str1), stdin) != NULL)
{
int i = 0, len = strlen(str2), tag = 0;
for (; i < len - 2; i++)
{
tag = 0;
if (str2[i] == 'y' && str2[i + 1] == 'o' && str2[i + 2] == 'u')
{
str2[i] = 'w';
str2[i + 1] = 'e';
tag = 1;
len--;
}
if (tag)
{
for (int j = i + 2; j < len + 1; j++)
str2[j] = str2[j + 1];
}
}
printf("%s", str2);
}
return 0;
}
错误代码
思路错误,采用了逐个单词判断的方式进行替换。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
char ch[5000];
int l = 0;
int main(int argc, const char *argv[])
{
// insert code here...
while (true)
{
ch[l++] = getchar();
if (ch[l - 1] == ' ')
{
ch[l - 1] = '\0';
if (strcmp(ch, "you") == 0)
printf("we ");
else
printf("%s ", ch);
l = 0; //完整单词输入完毕,开始下一个单词;
}
else if (ch[l - 1] == '\n')
{
ch[l - 1] = '\0';
if (strcmp(ch, "you") == 0)
printf("we\n");
else
printf("%s\n", ch);
l = 0;
}
else if (ch[l - 1] == EOF)
{
ch[l - 1] = '\0';
if (strcmp(ch, "you") == 0)
printf("we");
else
printf("%s", ch);
break;
}
}
return 0;
}
参考代码
#include <stdio.h>
#include <string.h>
int main()
{
// 声明两个字符数组,用于存储输入的字符串和替换后的字符串
char str1[1000];
char str2[1000];
// 通过循环使用 gets 逐行读取输入,直到文件结束
while (gets(str1))
{
// 获取当前字符串的长度
int len = strlen(str1);
int k = 0;
// 遍历字符串的每个字符
for (int i = 0; i < len; i++)
{
// 检查是否存在 "you",如果有,则在str2中存入 "we"
if (str1[i] == 'y' && str1[i + 1] == 'o' && str1[i + 2] == 'u')
{
str2[k] = 'w';
str2[k + 1] = 'e';
k += 2;
i += 2; // 跳过 "you" 的后两个字符 因为for循环本身有i++,所以此处是+2
}
else //其他字符正常存入
{
str2[k] = str1[i];
k++;
}
}
str2[k] = '\0'; // 在替换后的字符串末尾添加字符串结束标志
// 输出替换后的字符串
printf("%s", str2);
}
// 返回 0,表示程序正常结束
return 0;
}
(by 归忆)