How to count only the unique words from a string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

int get_total_unique_words(char str[]) {
    char *words[132];
    int uniqueCount = 0;
    int isUnique;

    // Split the string into words
    char *word = strtok(str, " ");
    while (word != NULL) {
        isUnique = 1;
        for (int i = 0; i < uniqueCount; i++) {
            if (strcmp(words[i], word) == 0) {
                isUnique = 0;
                break;
            }
        }
        if (isUnique) {
            words[uniqueCount] = word;
            uniqueCount++;
        }
        word = strtok(NULL, " ");
    }   
    
    return uniqueCount;
}

int main() {
    char str[] = "c c c++ java c++ rust c go rust c++ java";
    

    printf("Total unique words: %d\n", get_total_unique_words(str));

    return 0;
}


/*
run:

Total unique words: 5

*/


 



answered Sep 20, 2024 by avibootz

Related questions

1 answer 148 views
1 answer 114 views
1 answer 119 views
1 answer 113 views
1 answer 114 views
1 answer 153 views
1 answer 134 views
...