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

时间:2016-11-08 17:07:21

标签: 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;
}

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

1 个答案:

答案 0 :(得分:0)

以下内容应该有效:

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(输出数组)中的一个元素进行比较,如果 none 的话,它不是重复的ob比较平等。然后,您可以将此元素添加到ob并继续。