If I had an array of characters for example:
A = [w, o, r, n, g, , w, o, r, d]
And another array for example:
B = [c, o, r, r, e, c, t, , w, o, r, d, .]
I need to compare the words in array A (which are separated by a blank space) to array B and if any of the words in the first array exist in the second array, then that word should be printed. So for example, since “word” exists in the first array and in the second array, then “word” should be printed out.
How do I go about this?
Let’s see how I would do it:
You will need a function that, given an array of
char, splits it in an array of words (and put them in C strings, NUL terminated please 🙂 ). I would put the length of this array and the array in a structNow… How to do this function?
Let’s say we “cheat” a little and decide that our arrays
AandBare NUL terminated (or if they are.terminated like B, then you replace the.with a NUL). Now, this being C, you should first count the number of spaces in the string, allocate an array ofchar*(WordCollection::Words) big enough to containn + 1char*(and put thisn + 1inWordCollection::NumWords) and using strtok “tokenize” the string and put the words in the array you created.Then you should (could) split the A and B array in words using this function. You’ll obtain two
WordCollection, A1 and B1.To make it quicker, I would qsort B1.
Then for each word in A1 you bsearch it in B1 (it isn’t a bad word… It means Binary Search, and it’s a quick method of searching something in an ordered array)
Done 🙂
I’ll add that, if this is the first time you use
bsearchandqsort, it’s better you look at the samples you can find around. Their syntax can be “tricky”.Now… I know you won’t look at the code 🙂 so I’ll put it here
And on ideone