Java splits string into array

I need help using the split() method. I have the following String :

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

I need to put the values ​​in an array. 3 lines are possible: "0", "1" and ""

My problem is that I am trying to use split() :

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

My values ​​are only saved until the last 0. It seems that the "|||" part cropped. What am I doing wrong?

thank

+70
java string split
Jan 19 '13 at 12:54 on
source share
4 answers

This behavior is explicitly described in String.split(String regex) (my attention):

This method works as if it were calling a split method with two arguments with a given expression and a limit argument of zero. The resulting empty strings are therefore not included in the resulting array.

If you want to include these trailing blank lines, you need to use String.split(String regex, int limit) with a negative value for the second parameter ( limit ):

 String[] array = values.split("\\|", -1); 
+111
Jan 19 '13 at 13:00
source share

try it

 String[] array = values.split("\\|",-1); 
+23
Jan 19 '13 at 13:00
source share

Consider the following example:

 public class StringSplit { public static void main(String args[]) throws Exception{ String testString = "Real|How|To|||"; System.out.println (java.util.Arrays.toString(testString.split("\\|"))); // output : [Real, How, To] } } 

The result does not include blank lines between "|" separator. To save blank lines:

 public class StringSplit { public static void main(String args[]) throws Exception{ String testString = "Real|How|To|||"; System.out.println (java.util.Arrays.toString(testString.split("\\|", -1))); // output : [Real, How, To, , , ] } } 

For more information, go to this site: http://www.rgagnon.com/javadetails/java-0438.html

+7
03 Oct '14 at 15:14
source share

Expected. Refer to Javadocs for split .

 Splits this string around matches of the given regular expression. 

This method works as if you were calling the split method (java.lang.String, int) with two arguments with this expression and a limit argument of zero. Thus, trailing blank lines are not included in the resulting array.

+1
Jan 19 '13 at 12:58
source share



All Articles