Kotlin Convert Comma Separator String to List (KCCSSL)

This article discusses different ways to convert a comma separated string to a list in Kotlin.

The standard way to split a Kotlin string is by using the  split() function . This function converts a comma-separated string to a list in the following way:

1. Using the listOf() function

The idea is to split the string with the split() function and pass the resulting array to the listOf() function to get a new list.

fun  main () {
     val str = "A,B,C,D" 
    val list: List<String> = listOf(*str.split( "," ).toTypedArray())
 
    println(list)         // [A, B, C, D]
}

2. Using the toList() function

Another nice solution is to call the toList() function directly after splitting the array with split() .

fun  main () {
     val str = "A,B,C,D" 
    val list: List<String> = str.split( "," ).toList()
 
    println(list)         // [A, B, C, D]
}

3. Using the Pattern.compile() function

Finally, you can split the string using the split() function around a pattern match. This will translate into the simple code below:

import java.util.regex.Pattern
 
fun  main () {
     val str = "A,B,C,D"
 
    val list: List<String> = Pattern.compile( "," ).split(str).toList()
 
    println(list)         // [A, B, C, D]
}

4. Using the joinToString() function

The jointostring() function helps us convert a Kotlin List or Array into a single string. We can specify separator, prefix, postfix . If the List can have a large number of string items, we can provide a non-negative limit value, followed by the truncated string.

This is the prototype of the joinToString() function :

fun  joinToString (
    separator: CharSequence = ", " ,
    prefix: CharSequence = "" ,
    postfix: CharSequence = "" ,
    limit: Int = - 1 ,
    truncated: CharSequence = "..." ,
    transform: ((Char) -> CharSequence)? = null
): String

Let's look at some examples

val chars = listOf( 'a' , 'b' , 'c' , 'd' , 'e' )
 // [a, b, c, d, e]

chars.joinToString()
// a, b, c, d, e

chars.joinToString(prefix = "{" , postfix = "}" )
 // {a, b, c, d, e}

chars.joinToString(prefix = "{" , postfix = "}" , separator = "-" )
 // {abcde}

chars.joinToString(prefix = "{" , postfix = "}" , separator = "-" ) { it -> it.toUpperCase().toString() }
 // {ABCDE}

val nums = arrayOf( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 , 13 , 14 , 15 )

nums.joinToString(limit = 5 , truncated = "<...>" )
 // 1, 2, 3, 4, 5, <...>
	
nums.joinToString(limit = 5 , truncated = "<...>" ) { it -> (it * 2 ).toString() }
 // 2, 4, 6, 8, 10, <...>

Good luck!

Post a Comment

Previous Next

نموذج الاتصال