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.
splitaccepts a regular expression. The+character is a character with a special meaning in the context of regular expressions.String.split(String)treats the parameter as a regular expression where+has a special meaning. Trysplit(" \\+\\+ ")orsplit(Pattern.quote(" ++ "))instead.