分析两个字符串

时间:2013-10-23 17:16:35

标签: java string

给定两个字符串变量s1s2(s1 != s2)是否可以为真,而(s1.equals(s2))也是如此?

我会说不,因为如果String s1 = "Hello";String s2 = "hello"; 由于“h”与“H”不相等,但第二部分不可能是真的,因为当作为对象进行比较时它们也不相同。那会有意义吗?

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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)

答案 2 :(得分:0)

String s1 = new String("Hello");
String s2 = new String("Hello");

s1 == s2返回false

s1.equals(s2)返回true

因此,是的,这是可能的,因为默认情况下这些字符串不会在公共池内存中保存/检查,因为不是文字。