thingy
thingy

Reputation: 61

C, Count unique strings in an array of strings

Using C, I have an array of strings, some are duplicates. I'm trying to count the number of unique strings. Code:

 for(i=0; i<size; i++){
        flag=0;
        if(strcmp(" ", tArr[i])!=0){
            for(j=i; j<size; j++){
                if(strcmp(tArr[i], tArr[j])==0){
                    if (flag<1){
                        flag=1;
                        k++;
                    }
                    strcpy(tArr[j], " ");
                }
            }
        }
    }
  1. First for loop goes through the whole array

  2. Set flag to zero for each iteration

  3. Using blanks as another flag, if an index is blank, that means that word has already been counted, move to next index

  4. Compare that index to every index after it, thus j=i

  5. If the secondary index matches the first

  6. If that word has not been found yet

  7. Trigger the flag

  8. Add to k, the unique word count

  9. Set every remaining instance of that word to a blank space, to match line 3

    Instead of setting k to the unique word count, it gets set to the total word count. Using printed flags I was able to tell that the function makes it all the way through, even to after line

  10. I still can't tell how it makes it to line 8 every iteration of the outermost for loop.

Upvotes: 0

Views: 2530

Answers (1)

Segmented
Segmented

Reputation: 795

Adapting your code, try something like this:

for (i = 0; i < size; i++) {
    for (j = i + 1; j < size; j++)
        if (strcmp(tArr[i], tArr[j]) == 0)
            break;
    if (j == size)
        unique_count++;
}

There should be no need to destroy the duplicates if you are just counting, however if you still wish to do that I would suggest a null string instead of one containing a space.

Upvotes: 5

Related Questions