Search code examples
cstringcomparewords

How to compare two strings and return the number of words that are the same?


I am making a code in C, and I have not gotten an efficient way to make this comparison, if someone could help me I would be very grateful.

EXAMPLE:

W1: Big house with white walls W2: house walls

return: 2


Solution

  • When thinking how to solve the problem, it helps to break it down into steps that you can see clearly how to proceed, and how they progress toward the solution. The usual approach for something like this would be

    • make a copy of each string
    • for each string, make an array of pointers to char*, which
    • point into the copied strings, which in turn
    • parsed into "words" (putting '\0' at all of the non-word characters
    • run qsort on the array of strings

    Then, having two sorted arrays of pointers to words, you can write a loop using strcmp for checking equality of the words. I suggested strcmp because (since the arrays are sorted) it is simple to check when a word is missing from one or the other of the two arrays versus the other.

    The copy/parse/sort part would naturally be a function, given a string and returning the array of pointers. The caller should free that (and the chopped-up string to which it points).