Converting csv string into List of Int

I’m trying to convert a string string of items separated by , into list of Int, so I wrote this code:

fun main(args: Array<String>) {
    val regex = ","
    val lines = "30,21,29, 31, 40, 48, 53, 47, 37, 39, 31, 29, 17, 9, 20, 24, 27, 35, 41, 38, 27, 31, 27, 26, 21, 13, 21, 18, 33, 35, 40, 36, 22, 24, 21, 20, 17, 14, 17, 19, 26, 29, 40, 31, 20, 24, 18, 26, 17, 9, 17, 21, 28, 32, 46, 33, 23, 28, 22, 27, 18, 8, 17, 21, 31, 34, 44, 38, 31, 30, 26, 32"
	
    val series = lines.split(regex).toList().map{ it.toInt() }.toList<Int>()
    
    println(series)
}

But it did not work, and I got this error:

Exception in thread “main” java.lang.NumberFormatException: For input
string: " 31"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at Reading_many_names_from_the_command_lineKt.main(Reading many names from the command line.kt:5)

You need to add trim() to your pipeline, because space character doesn’t allow string to be parsed into integer value. Also you don’t need those toList() invocations, you already dealing with a lists, it’s not error but just redundant code. Here’s valid code:

val series = lines.split(regex).map { it.trim().toInt() }
2 Likes

You can also add the whitespaces to the regex as in:

val regex = "\\s*,\\s*"

But for general CSV support, hand rolling a parser is a bad idea since there other things that need to be supported like quoted strings for example.

This is a long solved problem: Commons CSV – Home

1 Like