【问题标题】:replace one word with another in a string将字符串中的一个单词替换为另一个单词
【发布时间】:2020-09-01 15:37:06
【问题描述】:

谁能告诉我这里的错误是什么。我在这里使用了二维数组。

    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char a[100], b[30][30], c[20], d[20];
        int i, j=0, k, count=0;
        int e[30];
        printf("enter a string: ");
        gets(a);
        printf("enter the word which has to be replaced: ");
        gets(c);
        printf("enter the word with which it has to be replaced: ");
        gets(d);
        for(i=0,k=0, e[i]=0; i<strlen(a); i++, k++)
        {
            if(a[i]==' ')
            {
                k=0;
                j++;
                count++;
            }
            else
            {
                b[j][k]=a[i];
                e[i]++;
            }
        }

        for(i=0; i<j; i++)
        {
            if(word(b[i], c)==0)
            {
                for(k=0; k<strlen(d); k++)
                {
                    b[i][k]=d[k];
                }
            }
        }
        for(i=0; i<count; i++)
        {
            for(j=0; j<e[i]; j++)
            {
                printf("%c", b[i][j]);
            }
            printf(" ");
        }
    }
    int word(char *a, char *c)
    {
        int i;
        if(strlen(a)==strlen(c))
        {
            for(i=0; i<strlen(a); i++)
            {
                if(a[i]!=c[i])
                {
                    return 1;
                }
            }
        }
        else
            return 2;
        return 0;
    }

我希望输出如下所示。 例如:

    enter a string: vicky is a good boy
    enter the word which has to be replaced: good
    enter the word with which it has to be replaced: bad
    vicky is a bad boy

我的意思是我只想替换那个特定的单词,就像它出现在字符串中一样多次,比如这里,单词 good。谁能帮我找出错误或帮我找到另一种方法。

【问题讨论】:

  • 使用描述性变量名,而不是abc
  • 你的程序看起来有点矫枉过正。逻辑没有那么复杂。例如,您可以使用strstr 定位"good"

标签: c arrays string multidimensional-array


【解决方案1】:

你不应该使用gets,这很危险:Why is the gets function so dangerous that it should not be used?

您应该改用fgets 来读取stdin

word函数中,你使用strlen函数比较两个字符串的长度:

if(strlen(a)==strlen(c))

但在主函数中,你称它为:

if(word(b[i], c)==0)

b[i] 是字符数组,但不要在每个单词的末尾添加空字符 \0。所以strlen 不会像你想象的那样工作。

在将字符串c 替换为d 的代码中。您没有更新 e 数组的值。 我认为,e[i] 应该是:

e[i] = strlen(d);

我好像你没有对字符串使用一些标准函数,例如对你的程序非常有用。

strcmp比较字符串和字符串。

strstr 在字符串中查找单词。

如果您在 google 中搜索,您可以有大量代码用于您的案例。

例如:program to Replace a word in a text by another given word

另一个:Replacing Words inside string in C

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2017-11-14
    • 2019-08-08
    • 1970-01-01
    相关资源
    最近更新 更多