有两个字符串,比如String a = "abcdefgbcd", b = "badcefgdcb",它们相比较返回true。另一对字符串,String x = "hello", y = "heoil",返回false。代码如下:
public void strCompare() {
String s = "ufncotin";
String str = "function";
if (s == null || s.trim().isEmpty()) {
System.out.println("NULL input");
}
char[] chars = s.toCharArray();
char[] charsStr = str.toCharArray();
System.out.println(chars);
System.out.println(charsStr);
System.out.println("****************************");
/*
* 先备份chars,不对原始数据操作,对它的备份操作,对str也一样,这里我就省略了
*/
char[] charsBackup = new char[chars.length];
System.arraycopy(chars, 0, charsBackup, 0, chars.length);
/*
* 对s中的元素和str中的元素排序
*/
Arrays.sort(charsBackup);
Arrays.sort(charsStr);
/*
* 还是原来的样子,没被排序所扰,上面不能使用
* char[] charsBackup = chars;
* 因为这样charsBackup和chars引用的内容一致,对charsBackup的操作会影响对
* chars所指向的内容
*/
System.out.println("chars:" + new String(chars));
System.out.println("charsBackup:" + new String(charsBackup));
System.out.println("charsStr:" + new String(charsStr));
/*
* 除非你重写它的equals和hashCode方法,不然下一行是不会返回true的
*/
System.out.println(chars.equals(charsStr));
/*
* 这样比较吧,把它们排序后转回String类型
*/
System.out.println(new String(charsBackup).equals(new String(charsStr)));
}