1

I got a String from a .csv and want to split it:

String line = "1,2,3,,,,false,true,,,false,false,,,,,,,,,,,,";
String data[] = line.split(",");

This is the result of the array:

data[0] - "1"
data[1] - "2"
data[2] - "3"
data[3] - ""
data[4] - ""
data[5] - ""
data[6] - "false"
data[7] - "true"
data[8] - ""
data[9] - ""
data[10] - "false"
data[11] - "false"

Why are the last "" lines cutted away from the array?

F. Baum
  • 301
  • 1
  • 5
  • 17

2 Answers2

1

Use the -1 parameter

String data[] = line.split(",", -1);

Check the javadoc

"The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded. "

When you specify no argument calling public String[] split(String regex) it uses default as 0.

From javadoc: "This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero."

anaxin
  • 710
  • 2
  • 7
  • 16
1

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)

the API says "Trailing empty strings are therefore not included in the resulting array."

Steve YonG
  • 80
  • 7