4

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.

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
ltd9938
  • 1,444
  • 1
  • 15
  • 29
  • 3
    `split` accepts a regular expression. The `+` character is a character with a special meaning in the context of regular expressions. – MC Emperor May 03 '19 at 14:15
  • 4
    `String.split(String)` treats the parameter as a regular expression where `+` has a special meaning. Try `split(" \\+\\+ ")` or `split(Pattern.quote(" ++ "))` instead. – Thomas May 03 '19 at 14:15

3 Answers3

8

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]);
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
0

Because ++ it's interpreted as a regular expression. You need to escape it with backslash. Try this:

System.out.println(x.split(" \\+\\+ ")[0]);

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
-1

Split method uses a regexp as argument, you should escape special characters like +. Try something like:

    String x = "Hello ++ World!";
    if(x.contains(" ++ "))
        System.out.println(x.split("\\s\\+\\+\\s")[0]);
Piotr S
  • 137
  • 3