Split String with multiple continuous commas in Java

String abc = "a,b,c,d,,,"; String[] arr = abc.split(","); System.out.println(arr.length); 

The result is 4. But, obviously, my expectation is 7. Here is my solution:

 String abc = "a,b,c,d,,,"; abc += "\n"; String[] arr = abc.split(","); System.out.println(arr.length); 

Why is this happening? Can anyone give me a better solution?

+6
source share
5 answers

Use an alternate version of String#split() , which requires two arguments:

 String abc = "a,b,c,d,,,"; String[] arr = abc.split(",", -1); System.out.println(arr.length); 

Will print

 7 

From the above Javadoc:

If n is not positive, the pattern will be applied as many times as possible, and the array can be of any length. If n is zero, the template will be applied as many times as possible, the array can be of any length, and the final empty lines will be discarded.

+7
source

You can use lookahead:

 String abc = "a,b,c,d,,,"; String[] arr = abc.split("(?=,)"); System.out.println(arr.length); //7 
+4
source

Using:

 String[] arr = abc.split("(?=,)"); 

for separation abc

+1
source

This is because split does not only include trailing blank lines, but if you have \n at the end, then the last element is not empty.

 [a, b, c, d, , , \n] 
+1
source

split () is encoded for this very job. You can count the occurrence of a character or line below.

  String ch = ","; int count = 0; int pos = 0; int idx; while ((idx = abc.indexOf(ch, pos)) != -1) { ++count; pos = idx + sub.length(); } System.out.println(count); 

This very logic is used in Spring.

0
source

All Articles