Is there a way to check if two strings contain the same characters. For example,
abc, bca -> true
aaa, aaa -> true
aab, bba -> false
abc, def ->
A very easy - but not very efficient - way to do that is, convert your String
s to char arrays and use java.util.Arrays.sort on them, get String
s back and compare for equality.
If your strings are under a few thousand characters, that should be very okay.
If you have several megabytes strings, you may want to create an array with a count for each character (using its code as an index), have one pass on one string adding one on the count of each char, and one pass on the second string removing one. If you fall under 0 at any point during the second pass, they don't have the same characters. When you're done with the second string without error, you are sure they have the same characters if they have the same length (which you should have checked first anyway).
This second method is much more complicated than sorting the strings, and it requires a big array if you want to work with unicode strings, but it's perfectly good if you're okay with only the 128 chars of the ascii set, and much faster.
Do NOT bother with that if you don't have several million characters in your strings. Sorting the strings is much easier, and not significantly slower on strings with only a couple dozen chars.