How to append strings separated by a comma in Kotlin
This article explores different ways to append strings separated by a comma in Kotlin.
There are several ways to convert a collection to a comma-separated String in Kotlin:
1. Using joinToString() function
The standard solution to join elements of a list with the specified delimiter is using the joinToString() function. Its usage is demonstrated below:
|
1 2 3 4 5 6 7 8 |
fun main() { val input = listOf(1, 2, 3, 4) val separator = ", " val str = input.joinToString(separator, transform = Int::toString) println(str) // 1, 2, 3, 4 } |
You can customize the output to our style as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main() { val input = listOf(1, 2, 3, 4) val str = input.joinToString( prefix = "[", separator = ", ", postfix = "]", limit = 3, truncated = "...", transform = Int::toString ) println(str) // [1, 2, 3, ...] } |
2. Using toString() function
The toString() function returns the string representation of the collection, which consists of all its elements, enclosed in square brackets [], and adjacent elements separated by the delimiter ", ".
|
1 2 3 4 5 6 7 |
fun main() { val input = listOf(1, 2, 3, 4) val str = input.toString() println(str) // [1, 2, 3, 4] } |
3. Using String.join() function
Another possibility to join strings together with a specified separator is with the java.lang.String.join() function, which only works for an Iterable<String>
|
1 2 3 4 5 6 7 8 |
fun main() { val words = listOf("A", "B", "C", "D") val separator = ", " val str = java.lang.String.join(separator, words) println(str) // A, B, C, D } |
4. Using String builder
Finally, you can create a utility function to traverse the list and append each element to a String builder with the specified delimiter. This logic would translate to the following code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
fun <T> join(list: List<T>): String { val sb = StringBuilder() var sep = "" for (e in list) { sb.append(sep).append(e) sep = "," } return sb.toString() } fun main() { val words = listOf("Hello", "World") val str = join(words) println(str) // Hello,World } |
That’s all about appending strings separated by a comma in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)