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 of Hello
?It obviously has something to do with the split()
, however, I can't figure it out.
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With