【发布时间】:2014-03-03 15:04:48
【问题描述】:
我有一些关于字符串比较的问题。我找不到任何关于替换和子字符串方法的答案。所以这里是代码
public static void main(String args[]) {
if ("hello".substring(0) == "hello")
System.out.println("statement 1 is true");
if ("hello".substring(1) == "ello")
System.out.println("statement 2 is true");
if ("hello".replace('l', 'l') == "hello")
System.out.println("statement 3 is true");
if ("hello".replace('h', 'H') == "Hello")
System.out.println("statement 4 is true");
if ("hello".replace('h', 'H') == "hello".replace('h', 'H'))
System.out.println("statement 5 is true");
}
输出是:
statement 1 is true
statement 3 is true
substring 方法是否创建了一个新的 String()。如果是,为什么语句 1 为真,而语句 2 不成立?语句 3 和 4 也有同样的问题。谢谢。
【问题讨论】:
-
在比较字符串相等性时切勿使用
==! -
是的,我知道我应该使用 equals,但我必须理解它。另外,我在 stackoverflow.com/questions/513832/… 上没有找到答案
标签: java string replace compare substring