【发布时间】:2015-04-20 15:30:50
【问题描述】:
我有这个作业问题:编写一个 C 程序,在使用函数反复将每次出现的 'foo' 替换为 'oof' 后,从输入字符串中删除子字符串 foo 的出现后找到新字符串。
这是我的代码:
#include <stdio.h>
#include <string.h>
void manipulate(char * a)
{
int i, flag = 0;
char newstr[100];
for (i = 0; a[i] != '\0'; i++) {
if (a[i] == 'f') {
if ((a[i + 1] != '\0') && (a[i + 1] == 'o')) {
if ((a[i + 2] != '\0') && (a[i + 2] == 'o')) {
i += 3;
flag++;
}
}
}
newstr[i] = a[i];
}
for (i = 0; i < flag; i++) {
strcat(newstr, "oof");
}
printf("\nThe output string is %s", newstr);
}
int main()
{
char a[100];
printf("Enter the input string");
scanf("%s",a);
manipulate(a);
return 0;
}
我认为我的代码有问题,因为预期的输出是:
Enter the input string
akhfoooo
The output string is akhoooof
但我的实际输出是:
Enter the input string
akhfoooo
The output string is akhoof
您能纠正我的代码中的错误吗?
【问题讨论】:
-
这个
scanf("%c",a);不应该是scanf("%s",a); -
谢谢,但即使更改后,我仍然没有得到预期的输出。
-
@geek_scuba_diver,karma_geek 是对的。对于您的编辑,请参阅我的回答。