gpt4 book ai didi

Java 字符串比较失败

转载 作者:行者123 更新时间:2023-12-01 16:48:26 25 4
gpt4 key购买 nike

为什么这个字符串比较失败?

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

}

最佳答案

您没有比较字符串。您正在比较 char 数组。数组不会覆盖 Objectequals,因此 equals 的行为与 == 相同。您可以从要比较的数组创建String,并对生成的String运行equals

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

关于Java 字符串比较失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45350471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com