When processing a csv String with an empty final field, myString.split( “,” ) returns incorrect number of array entries

江枫思渺然 提交于 2019-12-05 02:58:52

Figured it out as I was entering the question! Use stringObj.split( ",", numDelimitersExpected ) or, as @Supericy pointed out, stringObj.split( ",", -1 ).

According to the Android docs about stringObj.split( delimiter ) a call to line.split( "," ) is equivalent to a call to line.split( ",", 0 ) with the second argument referring to limit, which sets the 'maximum number of entries' and defines the 'treatment of trailing empty strings' . Looking at the documentation for stringObj.split( delimiter ) it states that with limit == 0 'trailing empty strings will not be returned'.

The solution is to use a call to split( ",", limit ) with limit set to the number of array entries you expect to get back. In my case a limit set to 5 returns the array

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

which is exactly what I wanted. Problem solved.

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

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

a call String values[] = toSplit.split( ",", 8 ) returns the array

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

Neat!

Note: Oracle's Java String.split( delimiter ) has the same functionality with the Android docs winning for their more concise explanation. (:

Edit: As @Supericy added, toSplit.split( ",", -1 ) would also properly return the trailing empty entry. Thanks for the addition!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!