How do I compare strings to see if they are composed of the same words

Posted 04 October 2012 - 12:13 PM

I need a method that can compare two strings and tells me if they are composed of the same words, regardless of the word order. For example, the method should return "true" (i.e. the strings are the same) when comparing these two strings:

Mary has a little lamp
Little lamp has a Mary

and return "false" (i.e. the strings are different) when comparing these two strings:

Re: How do I compare strings to see if they are composed of the same words

Posted 04 October 2012 - 01:21 PM

Take the two sentences and use string.split to break them into string arrays

sort each array

compare the elements now that they are in order
[0] to [0]
[1] to [1]
[2] to [2]
If they are of different sizes - fail.
If you get any element that doesn't match - fail.
If you can get to the end of each without a mismatch - success.

Now you have an algorithm to code up. Looking forward to seeing your code.

Re: How do I compare strings to see if they are composed of the same words

Posted 04 October 2012 - 01:54 PM

Since you said you wanted to match regardless of the order, I would like to add a little to what tlhIn`toq supplied. You will need to loop through the first array by its total number of elements and with each iteration of that loop, loop through each element of the second array to compare against the current element in the primary loop for comparison. The nice thing is, in any iteration of the primary loop, if there is not a match you can stop because the strings don't match.

EDIT:
One of these days tlhin`toq, I'm going to spell your handle correctly the first time.

Re: How do I compare strings to see if they are composed of the same words

Posted 04 October 2012 - 01:58 PM

No worries about the spelling, Charlie.

THough you don't need to do that nested loop business as that is going to increase the search time exponentially. That's the reason for sorting each array first - to take the original order out of consideration.

"Mary had a little lamp" and "A little lamp had Mary" would both sort to

a

had

lamp

little

Mary

Thus as long as [0] of each array are both "a", [1] of both arrays should be "had"... and so on.

Re: How do I compare strings to see if they are composed of the same words

Posted 04 October 2012 - 03:06 PM

Despite the lyrics of Weird Al Yankovich's "White and Nerdy" (I'm fluent in javascript as well as Klingon), not many developers actually speak Klingon. So the spelling TLHIN`TOQ does seem odd.

I had to change the normal apostophe (') to the accent (`) in the middle because it would also throw of the site parsing and turn tlhin'toq into tlhin because member='tlhin'toq' would naturally end at the second '