2016-11-08 106 views
0

我目前遇到代码的输出有问题。 它正确填充数组,但删除重复单词时出现问题。从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; 
} 

显然,输出打印输出阵列中的每一个字。我应该改变什么?什么我误解

+0

你永远不会重置'k'。所以你可能会在'ob [5]'上找到一个匹配的单词',下一次你进入'while'循环时,你的'strcmp'开始看着'ob [6]' – jiveturkey

回答

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

+1

不应该这样'if(k! = h)'be'if(k == h)' –

+0

是的,你是对的:当'k == h'时,没有检测到相等性。谢谢! (更新亩回答) –