ltd9938 :
Suppose I have this block of code:
String x = "Hello ++ World!";
if(x.contains(" ++ "))
System.out.println(x.split(" ++ ")[0]);
Why is it that when I execute this code I receive the output:
Hello ++ World!
instead ofHello
?
It obviously has something to do with the split()
, however, I can't figure it out.
Nikolas :
The method String::split
uses Regex for the split. Your expression " ++ "
is a Regex and the +
character has a special meaning. From the documentation:
Splits this string around matches of the given regular expression.
You have to escape these characters:
System.out.println(x.split(" \\+\\+ ")[0]);