Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare 2 strings containing same characters

Tags:

java

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.

like image 872
prasad Avatar asked Aug 23 '10 18:08

prasad


People also ask

How do you check if two strings have the same characters?

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.

How do you compare two strings with the same?

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.

Can you use == to compare two strings?

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.

What are the 3 ways to compare two string objects?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.


1 Answers

char[] chars1 = string1.toCharArray();
char[] chars2 = string2.toCharArray();
Arrays.sort(chars1);
Arrays.sort(chars2);

return Arrays.equals(chars1, chars2);
like image 158
Bozho Avatar answered Oct 06 '22 03:10

Bozho