How to Identify the Same Characters in 2 Different Strings

Hi All,

I am requiring a suggestion on how to identify the same characters in 2 different Strings, for example:

String str1 = "hello";

String str2 = "llheo";

Both Strings contain the same characters, but in a different order, so what would be the best technique to verify t that both Strings indeed contain the same characters?

I was personally thinking along the lines of using the class, java.util.regex.Pattern?

Any thoughts would me much appreciated. Thanks

[504 byte] By [testpressa] at [2007-10-3 4:03:46]
# 1

> Hi All,

>

> I am requiring a suggestion on how to identify the

> same characters in 2 different Strings, for example:

>

> String str1 = "hello";

>

> String str2 = "llheo";

>

> Both Strings contain the same characters, but in a

> different order, so what would be the best technique

> to verify t that both Strings indeed contain the same

> characters?

>

> I was personally thinking along the lines of using

> the class, java.util.regex.Pattern?

I would instead sort the characters, and then compare the sorted data.

Kaj

kajbja at 2007-7-14 22:02:50 > top of Java-index,Java Essentials,Java Programming...
# 2
Sorting is simplest, and Arrays.sort will sort character arrays, or you could use some kind of "crossing off" approach, where you look at each character in one string, and look for, and cross off a coresponding one in the second.
malcolmmca at 2007-7-14 22:02:50 > top of Java-index,Java Essentials,Java Programming...
# 3

If you wanted some method like:

boolean isAnagram(String word1, String word2);

I would use some sort of fail-fast approach.

e.g. first check if the strings are the same length. If not then you can return false without having to do the sorting etc. If they are the same length, you will then have to do the rest of the stuff (sorting etc). The return still might be false.

The average time for the method to return should be quicker.

Cheers,

Jim

patumairea at 2007-7-14 22:02:50 > top of Java-index,Java Essentials,Java Programming...
# 4

> I would instead sort the characters, and then compare

> the sorted data.

>

I'm fealing generous

private static boolean anagram(String left, String right)

{

if (left.length() != right.length())

return false;

char[] leftChars = left.toCharArray();

char[] rightChars = right.toCharArray();

Arrays.sort(leftChars);

Arrays.sort(rightChars);

return Arrays.equals(leftChars, rightChars);

}

sabre150a at 2007-7-14 22:02:50 > top of Java-index,Java Essentials,Java Programming...