首页 > 解决方案 > delete repeated following words in an array

问题描述

I got assignment to check string and to see if there is repeated words inside it

for example Source string: this is is a test test.

changes to: this is a test.

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

This is my code and the output that i'm getting is: this a test

As you can see the word 'is' deleted.

Another String: this is a test test to to this class.

Changes to: this a test to class.

Expected output: this is a test to this class.

Also delete the word 'is' and 'this'.

Any suggestions?

标签: c

解决方案


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

  • 它是第一个令牌,或者
  • 它与最后一个令牌不同

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

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

笔记:

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

推荐阅读