我有这个作业问题:使用函数通过反复地将'foo'的每个出现替换为'oof',使用函数从输入字符串中反复删除子字符串foo的出现之后,编写一个C程序来查找新字符串。
这是我的代码:
#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);
因为您要读取字符串,而不是单个字符。
编辑以进行编辑(请参阅评论):
#include <stdio.h>
#include <string.h>
void manipulate(char * a)
{
int i = 0;
char *pch;
size_t len = strlen(a);
while(a[i]) // until we do not reach the null terminator
{
// so that we do not go after the end of the string
if(i + 2 == len)
break;
// if we found 'foo'
if(a[i] == 'f' && a[i + 1] == 'o' && a[i + 2])
{
// replace it with 'oof'
a[i] = 'o';a[i + 1] = 'o'; a[i + 2] = 'f';
i = i + 2; // and check for after the replacement we just made
}
// increment our counter to check the next charachter
i = i + 1;
}
printf("\nThe output string is %s\n", a);
}
int main()
{
char a[100];
printf("Enter the input string");
scanf("%s",a);
manipulate(a);
return 0;
}
如果要使用函数,strstr()会很好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句