c - 删除数组中重复的以下单词

标签 c

我的任务是检查字符串并查看其中是否有重复的单词

例如 源字符串:这是一个测试测试。

更改为:这是一个测试。

void RemoveDuplicates(char *fixst) {
    char tempstr[N];
    char *subst = NULL;
    *tempstr = 0;
    subst = strtok(fixst, " ");
    if ((subst != NULL) && strstr(tempstr, subst) == NULL)
    {
        strcpy(tempstr, subst);
        while ((subst = strtok(NULL, " ")) != NULL) 
        {
            if (strstr(tempstr, subst) == NULL) 
            {
                strcat(tempstr, " ");
                strcat(tempstr, subst);
            }
        }
    }
    strcpy(fixst, tempstr);
}

这是我的代码,我得到的输出是:这是一个测试

如您所见,“is”一词已被删除。

另一个字符串:这是对该类的测试。

更改为:这是类测试。

预期输出:这是对该类的测试。

同时删除"is"和“这个”一词。

有什么建议吗?

最佳答案

下面的简单算法迭代输入字符数组中的每个标记/单词。当它找到新的标记/单词时,如果满足以下任一条件,它会将其复制到输出字符串:

  • 它是第一个 token ,或者
  • 它与最后一个标记不同

指向前一个标记的指针会在循环的每次迭代中更新 - 以方便比较。

void remove_duplicate_words(char *input) {
    size_t input_len = strlen(input);
    char *result = (char *)malloc(input_len + 1);
    if (!result) {
        fprintf(stderr, "Memory allocation failed!");
        return;
    }
    char *last_word = NULL;
    char *word = strtok(input, " ");

    while (word) {
        // Is this either the first word or different from the last word?
        if (last_word == NULL || strcmp(word, last_word) != 0) {
            // Yes -> append it to the output array
            strcat(result, word);
            strcat(result, " ");
        }
        last_word = word;
        word = strtok(NULL, " ");
    }

    puts(result);

    free(result);
}

注释:

  • 我在您的示例中使用了不同的变量名称 - 选择我认为更能清楚表达其含义的变量名称。
  • 输出数组(结果)的内存是根据输入字符串的长度动态分配的。 (我们知道它不能比输入数组长)。

关于c - 删除数组中重复的以下单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56575758/

相关文章:

c - 外部结构和多个 header

使用用户输入控制 POSIX 线程

c - 如何在 C 中正确检查 strptime 的有效日期

c - n叉树搜索函数

c++ - 判断一个数是否具有 P^Q 形式?

c++ - 为什么大型本地数组会使我的程序崩溃,而全局数组却不会?

c - 在 Win32 中等待串口传输完成

c - 混淆函数的返回值

c - 打印 0 而不是指定数字的基本功能 C

c - 访问冲突写入位置错误