Ami*_*cha 2 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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
您不是在比较字符串。您正在比较char. 数组不会覆盖Object's equals,因此equals行为与==. 您可以String从要比较的数组创建s,并equals在结果Strings上运行。
if(new String(temp).equals(new String(temp2)))
Run Code Online (Sandbox Code Playgroud)