Java: Split String around “+” [duplicate]

  • A+
Category:Languages

Just found out, that I get a NullPointerException when trying to split a String around +, but if I split around - or anything else (and change the String as well of course), it works just fine.

String string = "Strg+Q"; String[] parts = string.split("+"); String part1 = parts[0]; //Strg String part2 = parts[1]; //Q 

Would love to hear from you guys, what I am doing wrong!

This one works:

String string = "Strg-Q"; String[] parts = string.split("-"); String part1 = parts[0]; //Strg String part2 = parts[1]; //Q 


As + is one of the special regex syntaxes you need to escape it. Use

String[] parts = string.split("//+"); 

Instead of

String[] parts = string.split("+"); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: