Finding unique elements in a string array in C

C bothers me with its string handling. I have a pseudo code like in my head:

char *data[20]; 

char *tmp; int i,j;

for(i=0;i<20;i++) {
  tmp = data[i]; 
  for(j=1;j<20;j++) 
  {
    if(strcmp(tmp,data[j]))
      //then except the uniqueness, store them in elsewhere
  }
}

But when I encoded this, the results were bad. (I processed all the memory, little things, etc.). In the second cycle, the problem is explicit: D. But I can’t think of any solution. How to find unique strings in an array.

Input example: abc def abe abc def deg unique: abc def abe deg should be found.

+5
source share
5 answers

qsort, . , . - O (N log N), ( ) O (N ^ 2).

15- :

  typedef struct {
     int origpos;
     char *value;
  } SORT;

  int qcmp(const void *x, const void *y) {
     int res = strcmp( ((SORT*)x)->value, ((SORT*)y)->value );
     if ( res != 0 )
        return res;
     else
        // they are equal - use original position as tie breaker
        return ( ((SORT*)x)->origpos - ((SORT*)y)->origpos );
  }

  int main( int argc, char* argv[] )
  {
     SORT *sorted;
     char **orig;
     int i;
     int num = argc - 1;

     orig = malloc( sizeof( char* ) * ( num ));
     sorted = malloc( sizeof( SORT ) * ( num ));

     for ( i = 0; i < num; i++ ) {
        orig[i] = argv[i + 1];
        sorted[i].value = argv[i + 1];
        sorted[i].origpos = i;
        }

     qsort( sorted, num, sizeof( SORT ), qcmp );

     // remove the dups (sorting left relative position same for dups)
     for ( i = 0; i < num - 1; i++ ) {
        if ( !strcmp( sorted[i].value, sorted[i+1].value ))
           // clear the duplicate entry however you see fit
           orig[sorted[i+1].origpos] = NULL;  // or free it if dynamic mem
        }

     // print them without dups in original order
     for ( i = 0; i < num; i++ )
        if ( orig[i] )
           printf( "%s ", orig[i] );

     free( orig );
     free( sorted );
  }
+6
char *data[20];
int i, j, n, unique[20];

n = 0;
for (i = 0; i < 20; ++i)
{
    for (j = 0; j < n; ++j)
    {
        if (!strcmp(data[i], data[unique[j]]))
           break;
    }

    if (j == n)
        unique[n++] = i;
}

[0..n-1], .

+5

1?

+ 1. .

for(j=i+1;j<20;j++) 

abc
def
abc
abc
lop

== 4

TMP = ""

, 1 19. , 4 ,

[4], "lop", , tmp. , "lop" , .

, .

+2

Think a little more about your problem - what you really want to do is look at the PREVIOUS lines to make sure you have already seen this. So, for each line, ncompare it with the lines 0through n-1.

print element 0 (it is unique)
for i = 1 to n
  unique = 1
  for j = 0 to i-1 (compare this element to the ones preceding it)
    if element[i] == element[j]
       unique = 0
       break from loop
  if unique, print element i
+1
source

Perhaps this is your test if (strcmp (this, that)), which will succeed if they differ from each other ?! strcmp is probably what you want there.

0
source

All Articles