How to check if two strings have the same words in different order with C

1 Answer

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

int compare(const void *a, const void *b) {
    return strcmp(*(const char **)a, *(const char **)b);
}

int two_strings_have_same_words_in_different_order(const char *str1, const char *str2) {
    char *words1[128];
    char *words2[128];
    int count1 = 0, count2 = 0;

    char *token = strtok(strdup(str1), " ");
    while (token != NULL) {
        words1[count1++] = token;
        token = strtok(NULL, " ");
    }

    token = strtok(strdup(str2), " ");
    while (token != NULL) {
        words2[count2++] = token;
        token = strtok(NULL, " ");
    }

    qsort(words1, count1, sizeof(char *), compare);
    qsort(words2, count2, sizeof(char *), compare);

    if (count1 != count2) {
        return 0;
    }

    for (int i = 0; i < count1; i++) {
        if (strcmp(words1[i], words2[i]) != 0) {
            return 0;
        }
    }
    
    return 1;
}

int main() {
    const char *str1 = "java c# c c++ python";
    const char *str2 = "python c++ java c# c";
    const char *str3 = "python c++ java c# c rust";

    if (two_strings_have_same_words_in_different_order(str1, str2)) {
        printf("yes\n");
    } else {
        printf("no\n");
    }

    if (two_strings_have_same_words_in_different_order(str1, str3)) {
        printf("yes\n");
    } else {
        printf("no\n");
    }

    return 0;
}

 
 
/*
run:

yes
no

*/

 



answered Nov 28, 2024 by avibootz
...