Java字符串比较失败

3
为什么这个字符串比较失败?
package javaapplication57;

/**
*
* @author amit
*/
public class JavaApplication57 {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        String a = "anagram";
        String b = "margana";
        int len = a.length();
        char[] temp = a.toCharArray();
        char[] temp2 = b.toCharArray();
        int len2 = b.length();

        for(int j = 0; j<len-1; j++)
        {    
            for(int i = 0; i<len-1; i++)
            {
                if(temp[i]>temp[i+1])
                {
                    char t = temp[i];
                    temp[i] = temp[i+1];
                    temp[i+1] = t;
                }
            }
        }
        //System.out.println(temp);

        for(int j = 0; j<len2-1; j++)
        {    
            for(int i = 0; i<len2-1; i++)
            {
                if(temp2[i]>temp2[i+1])
                {
                    char t = temp2[i];
                    temp2[i] = temp2[i+1];
                    temp2[i+1] = t;
                }
            }
        }
        //System.out.println(temp2);
        if(temp.equals(temp2))
        {
            System.out.println("yes");
        }
    }

}

1
请解释一下您所说的“失败”是什么意思——您希望这段代码做什么,但它没有做到吗? - Hovercraft Full Of Eels
2
temp and temp2 are char[] and using equals between them does not work (it does not do what you think it does). Try this instead: if (Arrays.equals(temp, temp2)) - Jesper
问题到底是什么?它在哪里失败了?你的代码做了什么?它应该做什么? - Robert
@jesper 我们也可以提到,调用数组的equals方法会检查它们是否是同一个数组,而不是两个不同但相同的数组。 - Robert
3个回答

6

你并没有在比较字符串。你正在比较char数组。数组没有覆盖Objectequals,因此equals==的行为相同。你可以从你想要比较的数组创建String,并在结果的String上运行equals

if(new String(temp).equals(new String(temp2)))

2

只需要使用Java中的.equals方法即可。

String a = "anagram";
String b = "margana";
if(a.equals(b){
    System.out.pring("equals");
}else{
    System.out.pring("not equals";
}

1
假设您没有使用内置方法,您首先需要检查一个情况:两个字符串的长度必须相等。无需使用字符数组,只需遍历两个字符串,在检查长度是否相等后即可。
public static boolean equals(String str, String str2){

      if(str.length() != str2.length()){
         return false;
      }
      for(int i=0; i<str.length(); i++){
         if(str.charAt(i) != str2.charAt(i)){
            return false;
         }
      }
      return true;
   }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接