2017-07-27 116 views
0

为什么字符串比较失败?Java字符串比较失败

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

请解释“失败”是什么意思 - 你期望这段代码做什么,它没有做什么? –

+2

'temp'和'temp2'是'char []',并且在它们之间使用'equals'不起作用(它不会像你认为的那样)。试试这个:'if(Arrays.equals(temp,temp2))' – Jesper

+0

究竟是什么问题?它在哪里失败?你的代码是做什么的?它应该做什么? –

回答

4

你没有比较字符串。您正在比较char的数组。数组不会覆盖Objectequals,因此equals的行为与==相同。您可以从想要比较的阵列中创建String,然后在得到的String上运行equals

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

只需使用.equals方法从Java

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

假如你不使用内置的方法,你必须为的情况下,第一次检查:两个字符串的长度必须相等。在检查长度是否相等之后,不需要使用char数组就可以通过两个字符串。

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; 
    }