Java字符串比较失败

时间:2017-07-27 12:11:17

标签: java string comparison equals

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

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

}

3 个答案:

答案 0 :(得分:4)

你不是在比较字符串。您正在比较char的数组。数组不会覆盖Object的{​​{1}},因此equals的行为与equals相同。您可以从要比较的数组中创建==,并在生成的String上运行equals

String

答案 1 :(得分: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;
   }

答案 2 :(得分:0)

只需使用java中的https://[app-name].scm.azurewebsites.net方法

.equals
相关问题