【发布时间】:2013-03-14 05:47:46
【问题描述】:
我是一个相当新的程序员,作为我正在做的几个项目的一部分,我正在使用子字符串。在所有这些中,我都遇到了 if 语句的问题。假设我有两个变量,一个是其他字符串的子字符串,另一个应该与第一个子字符串等效。如果我尝试在 if 语句中检查它们是否相等(它们应该是),它会返回 false 和 == 检查。这里有一些代码来演示。
public class Substringproblem{
static void method(){
String random="somestring";
String randomsubstring=random.substring(0,3);
String should_be_randomsubstring="som";
if(randomsubstring==should_be_randomsubstring){
System.out.println("Success");
}else{
System.out.println("Failure");
System.out.println(randomsubstring);
}
}
public static void main(String[] args) {
method();
}
}
我觉得我错过了一些非常明显的东西,但我一直在寻找一些东西,但没有发现任何类似的东西。非常感谢您的帮助。
【问题讨论】:
-
如果要检查以某个字符串开头的字符串,可以使用
startsWith方法。无需遍历所有substring -
Awhh....还有很多其他问题解释相同...:\
-
尽快阅读《Head First Core Java》一书。用equals方法代替==
-
好的,这行得通。感谢所有给出答案的人。