Reputation: 61
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], " ");
}
}
}
}
First for loop goes through the whole array
Set flag to zero for each iteration
Using blanks as another flag, if an index is blank, that means that word has already been counted, move to next index
Compare that index to every index after it, thus j=i
If the secondary index matches the first
If that word has not been found yet
Trigger the flag
Add to k, the unique word count
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
I still can't tell how it makes it to line 8 every iteration of the outermost for loop.
Upvotes: 0
Views: 2530
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