繁体   English   中英

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

[英]Removing Repeated Words/Strings from an Array in C

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

逐字填充数组:

#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并继续。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM