My question is that, I have 2 strings, say String1 & String2. Now I want to check whether these 2 strings contain same characters or not, irrespective of their sequence.
Suppose String1= "qwerty"
, String2= "qywter"
. Now these Strings contain same characters but are in different sequence. So is there any function that can be used to show that these strings contain same characters?? Can equals() method do that???
All help is appreciated.
To check if two strings have the same characters:Use the sorted() function to sort the two strings. Use the equality operator to compare the results. If the comparison evaluates to True , the two strings have the same characters.
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
char[] chars1 = string1.toCharArray();
char[] chars2 = string2.toCharArray();
Arrays.sort(chars1);
Arrays.sort(chars2);
return Arrays.equals(chars1, chars2);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With