Java 分析两个字符串
给定两个字符串变量,Java 分析两个字符串,java,string,Java,String,给定两个字符串变量,s1和s2,(s1!=s2)是否可能为真,而(s1.equals(s2))是否也为真 我会说不,因为如果strings1=“Hello” 和String s2=“hello” 由于“h”和“h”的不同,不相等,但第二部分不可能为真,因为当作为对象进行比较时,它们也不相同。那有意义吗?是的。只需确保它们是相同的,但不是相同的引用(即,不要通过文本实习或使用字符串池)。下面是一个例子: String s1="teststring"; String s2 = new String(
s1
和s2
,(s1!=s2)
是否可能为真,而(s1.equals(s2))
是否也为真
我会说不,因为如果strings1=“Hello”代码>
和String s2=“hello”代码>
由于“h”和“h”的不同,不相等,但第二部分不可能为真,因为当作为对象进行比较时,它们也不相同。那有意义吗?是的。只需确保它们是相同的,但不是相同的引用(即,不要通过文本实习或使用字符串池)。下面是一个例子:
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.
对。只需确保它们是相同的,但不是相同的引用(即,不要通过文本实习或使用字符串池)。下面是一个例子:
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.
s1==s2
返回false
s1.equals(s2)
返回true
因此,是的,这是可能的,因为默认情况下,这些字符串不会在公共池内存中保存/检查,因为它们不是文本
s1==s2
返回false
s1.equals(s2)
返回true
因此,是的,这是可能的,因为默认情况下,这些字符串不在公共池内存中保存/检查,因为它们不是文本。对于两个字符串,s1
和s2
(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=“你好世界”
和s2=“你好世界”
:
在s1=“Hello World”
和s2=“Hello World”
的情况下
最后,如果要进行不区分大小写的比较,可以执行以下操作:
(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)
对于两个字符串,s1
和s2
(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=“你好世界”
和s2=“你好世界”
:
在s1=“Hello World”
和s2=“Hello World”
的情况下
最后,如果要进行不区分大小写的比较,可以执行以下操作:
(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)
具有相同内容的两个不同字符串对象将满足这些条件。您对这一个有何看法:stringa=newstring(“ABC”);字符串b=新字符串(“ABC”)代码>?这两个都应该满足您的两个条件。两个具有相同内容的不同字符串对象将满足这些条件。您如何看待这一个:stringa=newstring(“ABC”);字符串b=新字符串(“ABC”)代码>?这两个条件都应该适用。这说明了这些比较的作用,而不是如何得到OP想要的结果。它解释了它背后的概念,但要注意你写的是指针,而不是引用。现在有意义了!谢谢@我认为我的答案现在提供了一个更完整的解释。这说明了这些比较的作用,而不是如何得到OP想要的结果。它解释了它背后的概念,但注意你写的是指针而不是引用。现在有意义了!谢谢@我想我的答案现在提供了一个更完整的解释。