任意输入字符串,将该字符串中"yes"替换成"no".#include<stdio.h> #include<string.h> int main() { char s[100],s1[100]; int i,j; gets(s); for(i=0,j=0;i<strlen(s);) if(s[i]=='y'&&s[i+1]=='e'&&s[i+2]=='s') { s1[j++]='n'; s1[j++]='o'; i+3;} else s1[j++]=s[i++]; puts(s1); return 0; }为什么实现不了
时间: 2024-03-09 20:51:04 浏览: 24
代码中的问题在于 if 语句中的 i+3 没有被赋值给 i,导致 i 没有被更新,程序会一直停留在字符串中的 "yes",导致无法继续遍历。修改代码中的 i+3 为 i=i+3 即可解决问题,代码如下:
```c
#include <stdio.h>
#include <string.h>
int main() {
char s[100], s1[100];
int i, j;
gets(s);
for(i = 0, j = 0; i < strlen(s); ) {
if(s[i] == 'y' && s[i+1] == 'e' && s[i+2] == 's') {
s1[j++] = 'n';
s1[j++] = 'o';
i = i + 3;
} else {
s1[j++] = s[i++];
}
}
puts(s1);
return 0;
}
```
需要注意的是,代码中的 gets 函数容易导致缓冲区溢出,建议使用 fgets 函数代替。
相关问题
编写C语言,使任意输入字符串,将该字符串中"yes"替换成"no".
好的,以下是C语言的示例代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入字符串:");
fgets(str, 100, stdin); // 使用fgets函数接收字符串,防止溢出
int len = strlen(str);
for (int i = 0; i < len - 2; i++) {
if (str[i] == 'y' && str[i + 1] == 'e' && str[i + 2] == 's') { // 找到"yes"字符串
str[i] = 'n';
str[i + 1] = 'o';
str[i + 2] = '\0'; // 将"yes"替换为"no"
}
}
printf("替换后的字符串为:%s", str);
return 0;
}
```
这个程序会把任何输入的字符串中的 "yes" 替换为 "no",并输出替换后的字符串。
请用c语言解决,任意输入字符串,将该字符串中"yes"替换成"no".
好的,以下为使用C语言解决的代码:
```
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
char output[100];
int i, j, len;
printf("请输入字符串:");
scanf("%s", str);
len = strlen(str);
for (i = 0, j = 0; i < len; i++) {
if (str[i] == 'y' && str[i + 1] == 'e' && str[i + 2] == 's') {
output[j++] = 'n';
output[j++] = 'o';
i += 2;
} else {
output[j++] = str[i];
}
}
output[j] = '\0';
printf("替换后的字符串为: %s", output);
return 0;
}
```
以上程序中,我们定义了两个字符数组 `str` 和 `output`,输入的字符串存放在 `str` 中,通过循环遍历 `str` 中的每个字符来查找 "yes",如果找到,则将 "no" 存储到 `output` 中,如果未找到,则将原来的字符存储到 `output` 中。最后,输出替换后的字符串 `output` 即可。