2013-10-23 73 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