2015-04-02 92 views
-3

如何比較2個特殊字符的字符串? 我有如下字符串,我可以知道如何比較兩者嗎?比較在特殊字符的jave中的2個字符串

strA = "AC-11234X-DD+++1" 
strB = "AC-11234X-DD+++1" 

我測試matches()equals()equalsIgnoreCase()都不能正常工作。

if (strA.matches(strB)){ 
... 
} else { 
.. 
} 
+4

'的System.out.println (「AC-11234X-DD +++ 1」.equals(「AC-11234X-DD +++ 1」));'打印'true'。究竟是什麼問題? – JonK 2015-04-02 08:27:28

+0

這裏沒有*特殊*字符..'equals()'將完成作業 – TheLostMind 2015-04-02 08:27:45

+0

在這裏使用equals。 – Brunaldo 2015-04-02 08:28:55

回答

-1

此代碼檢查,如果這兩個字符串相等或不

String strA = "AC-11234X-DD+++1" ; 
String strB = "AC-11234X-DD+++1";  

if(strA.equals(strB)) 
     //they are equal 
else 
     //they are not 
+1

我不確定你是否看過這個問題,OP明確說'equals()'不適合他,需要先理解* why,但他已經嘗試過了。 – amit 2015-04-02 08:28:09

+0

@amit我讀的問題的字符串是相同的,所以他/她可以使用equals方法來檢查字符串是否相等,我沒有看到你的compareTo或其他任何需要:) – Arlind 2015-04-02 08:33:19

+0

@Arlind well said ur right – abhi 2015-04-02 08:36:07

0

你爲什麼不嘗試

的System.out.println(strA.hashCode()== strB.hashCode ());

如果matches(),equals(),equalsIgnoreCase()不起作用。

如果您對此結果不滿意,您可以嘗試覆蓋compareTo方法並擁有自己的邏輯。

+1

哈希不保證是唯一的,它們對於不同的字符串可以是相同的,比如''Aa''和''BB「'所以'strA.hashCode()== strB.hashCode()'不是最好的方法。 – Pshemo 2015-04-02 08:57:02

-1
public static void main(String[] args) 
{ 
    String strA = "AC-11234X-DD+++1"; 
    String strB = "AC-11234X-DD+++1"; 

    System.out.println(strA.equals(strB)); 
    } 

這很好用。

+1

「是否適用於我」答案有效?(http://meta.stackexchange.com/questions/118992/are-works-for-me-answers-valid) – Pshemo 2015-04-02 08:52:38

-1

必須使用compareTo方法。

通過此方法返回的值是一個INT

  • 如果是> 0意味着,第二串之前按字母順序
  • 第一,如果它是= 0指的是兩個串是平等的;
  • 如果是< 0表示最前一頁字符串之前關於你的問題可能是出在按字母順序排列第二

一個例子(很粗糙):

int r = A.compareTo(B); 

if(r > 0) { 
    System.out.println("B comes before A in alphabetical order"); 
} else if(r < 0) { 
    System.out.println("A comes before B string in alphabetical order"); 
} else { 
    System.out.println("The two strings are equal"); 
} 
+1

「*必須使用compareTo方法。*」爲什麼?如果字符串相等,這應該與'equals'一起工作,不需要'compareTo'。 – Pshemo 2015-04-02 09:00:41