繁体   English   中英

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

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

我有这个作业问题:使用函数通过反复地将'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()会很好。

这样就可以了。 注意边界条件和何时退出。

#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;
      }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM