Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to split a string on plus signs?

I was trying to split an arithmetic expression (eg "1+2+10+15") on the plus signs. However, I didn't manage to write the appropriate regular expression. I thought this would work:

expression.split("\\+"); 

but it doesn't. Do you know the correct solution?

like image 478
John Manak Avatar asked Feb 04 '10 08:02

John Manak


People also ask

How do you break a string with special characters?

To split a string by special characters, call the split() method on the string, passing it a regular expression that matches any of the special characters as a parameter. The method will split the string on each occurrence of a special character and return an array containing the results. Copied!

How do you split a string with double quotes?

split("(? =\"[^\"]. *\")");

How do you break apart a string in Java?

split("-"); We can simply use a character/substring instead of an actual regular expression. Of course, there are certain special characters in regex which we need to keep in mind, and escape them in case we want their literal value. Once the string is split, the result is returned as an array of Strings.

How do you split a string with a period?

To split a string with dot, use the split() method in Java. str. split("[.]", 0);


2 Answers

It does. However split(...) returns an array, it does not "transform" your String into a String[]. Try this:

String expression = "1+2+10+1"; String[] tokens = expression.split("\\+"); 
like image 70
Bart Kiers Avatar answered Sep 22 '22 05:09

Bart Kiers


this way

expression.split("[+]"); 
like image 28
mikail Avatar answered Sep 22 '22 05:09

mikail