c - 从 C 数组中删除重复的单词/字符串

标签 c arrays

我目前在代码输出方面遇到问题。 它正确填充数组,但我删除重复单词时出现问题。

逐字填充数组:

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

int main(void) {
char str[610] = "C (pronounced like the letter C) is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. Although Cwas designed for implementing system software, it is also widely used for developing portable application software. C is one of the most widely used programming languages of all time and there are very few computer architectures for which a C compiler does not exist. C has greatly influenced many other popular programming languages, most notably C++, which began as an extension to C.";
char tokChars[9]=" ;().,\n";
char *cptr;
int size = 100;
char array[1000][20];
char ob[1000][20];
int  count;
int i= 0;
cptr = strtok(str, tokChars);
count = 1;

while(cptr != NULL)
       {
            strcpy(array[i], cptr);
            printf("\n%s\n",array[i]);
            printf("token %d --> %s \n",count , cptr);
            cptr = strtok(NULL, tokChars);
            count++;
            i++;
       }

要删除重复的单词:

int k = 0, r = 0,h = 0;
for(r= 0 ; r<100 ; r++)
{
    while ( k< 100)
    {
        int a;
        a = strcmp(array[r], ob[k]);
         if (a != 0)
         {
             strcpy(ob[h],array[r]);
             h++;

             break;
         }


         k++;
    }
}

int m = 0;
for(m= 0; m<size; m ++)
{
    printf("\n%s\n",ob[m]);
}
return EXIT_SUCCESS;
}

显然输出打印出了数组中的每个单词。我应该改变什么?或者我误解的东西

最佳答案

以下应该有效:

int k, r, h;

strcpy(ob[0],array[0]); h= 1;
for(r= 0 ; r<100 ; r++)
{
    k= 0;
    while (k< h)
    {
        if (strcmp(array[r], ob[k]) == 0)
             break;
         k++;
    }
    if (k==h) {
        strcpy(ob[h],array[r]);
        h++;
    }
}

主要问题是您将 array 的下一个元素与 ob(输出数组)的一个元素进行比较,如果 ob 中没有一个比较相等。然后您可以将此元素添加到 ob 并继续。

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

相关文章:

c - 使用赋值和 printf 时出现段错误 11

c - 如何在 GnuWin32 Flex 中从另一个标记/表达式中排除一个标记/表达式

java - 从数组中删除左侧重复项

javascript - 如何使用数据库列值作为引用,使用 PHP 重新排序(或创建新的)Javascript 数组

java带有数组和int的新构造函数

c - 如何检查字符串是否在 C 中的字符串数组中?

c - 此 C 继承实现是否包含未定义的行为?

c - 如何使用GDI将RGB位图绘制到窗口?

c++ - 确定 Windows Server 2003 SP 1 是 32 位还是 64 位的正确方法是什么?

c - 如何将数组中的字符转换为字符串