从输入字符串中重复删除和替换子字符串的出现

Repeatedly removing and replacing the occurence of a substring from the input string

我有这个家庭作业问题:编写一个 C 程序,通过使用函数将每次出现的 'foo' 重复替换为 [=24,重复从输入字符串中删除出现的子字符串 foo 来查找新字符串=].

这是我的代码:

#include <stdio.h>
#include <string.h>

void manipulate(char * a)
{
    int i, flag = 0;
    char newstr[100];

    for (i = 0; a[i] != '[=10=]'; i++) {
        if (a[i] == 'f') {
            if ((a[i + 1] != '[=10=]') && (a[i + 1] == 'o')) {
                if ((a[i + 2] != '[=10=]') && (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()会很好。

这会很好用。 注意边界条件和何时退出。

#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
    {
    // if we found 'foo'
    if(a[i] == 'f' && a[i + 1] == 'o' && a[i + 2]=='o')
    {
    // replace it with 'oof'
    a[i] = 'o';a[i + 1] = 'o'; a[i + 2] = 'f';
    if ( i+3 == len){
    break;
    }
    else{

    i = i + 2; // and check for after the replacement we just made
    continue;
    }
    }
    else
{
    i = i+1;
}
    }
    printf("\n\n\nThe output string is %s \n", a);
    }

int main()
     {
     char a[100];

      printf("Enter the input string \n");
      scanf("%s",a);
      manipulate(a);

       return 0;
      }