Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java split string to array [duplicate]

Tags:

java

string

split

I need help with the split() method. I have the followingString:

String values = "0|0|0|1|||0|1|0|||"; 

I need to put the values into an array. There are 3 possible strings: "0", "1", and ""

My problem is, when i try to use split():

String[] array = values.split("\\|");  

My values are saved only until the last 0. Seems like the part "|||" gets trimmed. What am i doing wrong?

thanks

like image 748
Dusan Avatar asked Jan 19 '13 12:01

Dusan


1 Answers

This behavior is explicitly documented in String.split(String regex) (emphasis mine):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):

String[] array = values.split("\\|", -1); 
like image 196
Mark Rotteveel Avatar answered Nov 15 '22 13:11

Mark Rotteveel