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 ->
As a (nitpicking ;-) ) side note:
Be aware that the solutions proposed here only work for strings composed of characters from the Basic Multilingual Plane (BMP) of Unicode.
Characters outside the BMP are represented as a pair of char
in a String
, so you need to pay extra attention, so you keep the pairs together. See the Javadocs of java.lang.Character
for the gory details.
Fortunately, most characters outside the BMP are rather exotic. Even most of Japanese and Chinese is in the BMP...
Here:
import java.util.Arrays;
public class CompareString {
String str = "Result";
String str1 = "Struel";
public void compare() {
char[] firstString = str.toLowerCase().toCharArray();
char[] secondString = str1.toLowerCase().toCharArray();
Arrays.sort(firstString);
Arrays.sort(secondString);
if (Arrays.equals(firstString, secondString) == true) {
System.out.println("Both the string contain same charecter");
} else {
System.out.println("Both the string contains different charecter");
}
}
public static void main(String[] args) {
CompareString compareString = new CompareString();
compareString.compare();
}
}
Consider creating a signature for a given String. Using count and character.
a-count:b-count:c-count:.....:z-count:
(extend for upper case if you want ).
Then compare the signature. This should scale better for very large Strings.
As a shortcut, check the length. If they are not matching, return false anyway.
here:
String str1 = "abc";
String str2 = "cba";
/* create sorted strings */
/* old buggy code
String sorted_str1 = new String( java.utils.Arrays.sort(str1.toCharArray()) );
String sorted_str2 = new String( java.utils.Arrays.sort(str2.toCharArray()) );
*/
/* the new one */
char [] arr1 = str1.toCharArray();
char [] arr2 = str2.toCharArray();
java.utils.Arrays.sort(arr1);
java.utils.Arrays.sort(arr2);
String sorted_str1 = new String(arr1);
String sorted_str2 = new String(arr2);
if (sorted_str1.equals( sorted_str2 ) ) {
/* true */
} else {
/* false */
}