This question already has an answer here:
这个问题在这里已有答案:
- How do I compare strings in Java? 23 answers
如何比较Java中的字符串? 23个答案
Both strings appear to be the same when printed to the console, but not when compared using "=="
打印到控制台时,两个字符串看起来都相同,但使用“==”进行比较时则不一样
What am i doing wrong here?
我在这做错了什么?
String message = "Rejected | Ref ID: CaptureMe | Name:";
Pattern pattern = Pattern.compile("\\bRef ID:\\s+(\\S+)");
Matcher matcher = pattern.matcher(message);
String matchedRef = matcher.group(1);
System.out.print(matchedRef);
Prints: CaptureMe
String myRef = "CaptureMe";
if(matchedRef == myRef){
System.out.print(true);
}
else{
System.out.print(false);
}
Prints: FALSE
1 个解决方案
#1
2
To compare strings you need to use the equals()
method, not the ==
operator.
要比较字符串,您需要使用equals()方法,而不是==运算符。
if(matchedRef.equals(myRef)){
System.out.print(true);
}
else{
System.out.print(false);
}
You can read more about String
comparisons in this question.
您可以在此问题中阅读有关字符串比较的更多信息。
#1
2
To compare strings you need to use the equals()
method, not the ==
operator.
要比较字符串,您需要使用equals()方法,而不是==运算符。
if(matchedRef.equals(myRef)){
System.out.print(true);
}
else{
System.out.print(false);
}
You can read more about String
comparisons in this question.
您可以在此问题中阅读有关字符串比较的更多信息。