When processing a csv string with an empty end field myString.split (",") returns the wrong number of array entries

I process a specific string read from a CSV file using String.split(",") , and find that the final empty string after the last separator does not turn it into an array created by the split function.

Here are the values ​​of the variables that cause the error:

 String toSplit = "1,Some Value,31337,Another Value,"; String[] values = toSplit.split( "," ); 

The values array ends up being less than the expected number of array entries. Created Array:

 values[0] : '1' values[1] : 'Some Value' values[2] : '31337' values[3] : 'Another Value' 

when values[4] throws an ArrayIndexOutOfBounds exception.

The array I want:

 values[0] : '1' values[1] : 'Some Value' values[2] : '31337' values[3] : 'Another Value' values[4] : '' 

One caveat: I am reading the output of another creator of the .csv file and do not want to use line delimiters or throwing a space character in places where the data is empty. (i.e. do not want: toSplit = "1,Some Value,31337,Another Value, " with a space at the end.)

Is this a bug in String.split () and is there a workaround / other option?

+8
java android string split string-split
source share
1 answer

Thought when I went into the question! Use stringObj.split (",", numDelimitersExpected) or, as @Supericy noted, stringObj.split (",", -1) .

According to Android docs about stringObj.split (delimiter), calling line.split( "," ) equivalent to calling line.split( ",", 0 ) with the second argument related to limit , which sets the "maximum number of entries" and defines "handling trailing blank lines." Looking at the documentation for stringObj.split (delimiter) , she states that if limit == 0 ', the final empty lines will not be returned .

The solution is to use the split( ",", limit ) call with limit for the number of array entries that you expect to receive . In my case, the restriction set to 5 returns an array

 values[0] : '1' values[1] : 'Some Value' values[2] : '31337' values[3] : 'Another Value' values[4] : '' 

what I wanted. The problem is resolved.

In fact, even if your toSplit line has fewer delimiters than limit , a call with the set limit will still create empty entries in the array up to limit . For example, with the same intro line as in my question:

 String toSplit = "1,Some Value,31337,Another Value," 

calling String values[] = toSplit.split( ",", 8 ) returns an array

 values[0] : '1' values[1] : 'Some Value' values[2] : '31337' values[3] : 'Another Value' values[4] : '' values[5] : '' values[6] : '' values[7] : '' 

Well maintained!

Note: Oracle Java String.split (delimiter) has the same functionality as Android winnings, for their more concise explanations. (

Edit: as you add @Supericy toSplit.split( ",", -1 ) will also correctly return the final empty record . Thanks for adding!

+13
source share

All Articles