Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Split String around "+" [duplicate]

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
like image 459
Bambi Avatar asked Apr 18 '26 15:04

Bambi


2 Answers

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

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

Instead of

String[] parts = string.split("+");
like image 121
Amit Bera Avatar answered Apr 21 '26 03:04

Amit Bera


Try this:

final String string = "Strg+Q";
final String[] parts = string.split("\\+");
System.out.println(parts[0]); // Strg
System.out.println(parts[1]); // Q
like image 23
Arun Avatar answered Apr 21 '26 03:04

Arun