[英]Java String Comparison fails
為什么此字符串比較失敗?
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
數組。 數組不會覆蓋Object
的equals
,因此equals
行為與==
相同。 您可以從要比較的數組中創建String
,並在結果String
上運行equals
。
if(new String(temp).equals(new String(temp2)))
假設您未使用內置方法,則必須首先檢查以下情況:兩個字符串的長度必須相等。 在檢查長度是否相等后,無需遍歷兩個字符串就無需使用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;
}
只需使用Java中的.equals
方法
String a = "anagram";
String b = "margana";
if(a.equals(b){
System.out.pring("equals");
}else{
System.out.pring("not equals";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.