2013-10-23 74 views
1

給定兩個字符串變量s1s2(s1 != s2)爲真是可能的,而(s1.equals(s2))也是如此嗎?分析兩個字符串

我會說不,因爲如果String s1 = "Hello";String s2 = "hello"; 不等於由於「H」與「H」,而是因爲當作爲對象相比它們並不相同,以及第二部分不是真的呢。這有道理嗎?

+0

兩個不同的字符串對象,具有相同的內容將滿足這些條件。 –

+0

你對這個有什麼看法:'String a = new String(「ABC」);字符串b =新字符串(「ABC」);'?這兩個都應該保持你的兩個條件。 –

回答

2

是的。只要確保它們是相同的但不是相同的引用(即不要實習或通過文字使用字符串池)。這裏有一個例子:

String s1="teststring"; 
String s2 = new String("teststring"); 
System.out.println(s1 != s2); //prints true, different references 
System.out.println(s1.equals(s2)); //true as well, identical content. 
0
String s1 = new String("Hello"); 
String s2 = new String("Hello"); 

s1 == s2回報false

s1.equals(s2)回報true

因此,是的,這是可能的,因爲這些字符串不被保存/默認情況下,一個共同的池內存中進行檢查因爲不是字面的。

2

兩個字符串,s1s2

(s1 != s2)  //Compares the memory location of where the pointers, 
       //s1 and s2, point to 

(s1.equals(s2) //compares the contents of the strings 

所以,s1 = "Hello World"s2 = "Hello World"

(s1 == s2) //returns false, these do not point to the same memory location 
(s1 != s2) //returns true... because they don't point to the same memory location 

(s1.equals(s2)) //returns true, the contents are identical 
!(s1.equals(s2)) //returns false 

s1 = "Hello World"s2 = "hello world"的情況下,

(s1.equals(s2)) //This returns false because the characters at index 0 
       //and 6 are different 

最後,如果你想不區分大小寫的比較,你可以這樣做:

(s1.toLowerCase().equals(s2.toLowerCase())) //this will make all the characters 
              //in each string lower case before 
              //comparing them to each other (but 
              //the values in s1 and s2 aren't 
              //actually changed) 
+0

這就是說這些比較是做什麼的,而不是如何得到OP想要的結果。 – hexafraction

+0

這是解釋它背後的概念,但要小心你寫指針而不是引用。 – JNL

+0

@JNL修好了,謝謝。 – nhgrif