2013-05-13 100 views
0

我試圖比較兩個字符串代碼:的Equals結果編輯字符串假

public class MyClass 
{ 
    public static void main(String args[]) 
    { 
    String xhex="31 38 30 2E 32 35 35 2E 32 32 35 2E 31 32 33"; 
    String hex = remspace(xhex).trim().toString(); 
    System.out.println(hex); 
    String hex1="3138302E3235352E3232352E313233"; 
    System.out.println(hex1); 
    if(hex.trim().equalsIgnoreCase(hex1.trim())) 
    //if (hex.equals(hex1)) 
     { 
     System.out.println("equals"); 
     }else 
     { 
     System.out.println("not equals"); 
     } 
} 

private static String remspace(String data) 
    { 
     String xdata = null; 
     char c='\0'; 
     String hex = data.replace(' ',c); 
     return hex; 
    } 
} 

結果是:

3138302E3235352E3232352E313233 
3138302E3235352E3232352E313233 
not equals 

我們可以看到的結果是相同等於但是當我試圖比較字符串使用等於結果不等於。任何想法爲什麼它認爲不等於?

+0

有可能會出現一些新行或一個非打印字符。嘗試將其分割爲char數組並進行比較。 – NeplatnyUdaj 2013-05-13 11:13:59

回答

0

這個工作對我來說:

public static String removeWhitespaces(String source){ 
    char[] chars = new char[source.length()]; 
    int numberOfNewlines = 0; 
    for (int i = 0; i<chars.length; i++){ 
     if (source.charAt(i)==' ') 
      numberOfNewlines++; 
     else 
      chars[i-numberOfNewlines]=source.charAt(i); 
    } 
    return new String(chars).substring(0, source.length()-numberOfNewlines); 
} 
+0

非常感謝。這正是我需要的 – Ferry 2013-05-13 12:33:29

8

它們並不相同,第一個字符串在空間曾經是的地方有'\0'。它們僅在控制檯上顯示爲相同,因爲不顯示。

如果你想的空間被刪除的使用,改變remspace方法:

private static String remspace(String data) { 
    return data.replace(" ", ""); 
} 
+0

是否有任何想法來取代白色空間?僅供參考我正在使用STIPML,因此函數replace(「」,「」)不能使用,因爲該方法只能讀取char而不是字符串。該片段顯示 String類型的替換(char,char)不適用於參數(String,String) – Ferry 2013-05-13 11:21:17

+0

使用單引號 – NeplatnyUdaj 2013-05-13 11:22:06

+0

@NeplatnyUdaj當我使用單引號時,它顯示無效的字符常量錯誤 – Ferry 2013-05-13 11:25:16