Convert a list to a string in Kotlin
This article explores different ways to convert a list to a string in Kotlin. All elements in the specified list should be joined into a single string separated by a delimiter. The solution should not add the delimiter before or after the string.
1. Using joinToString() function
The standard solution to join strings together with a specified delimiter is with the joinToString() function. This is demonstrated below:
|
1 2 3 4 5 6 7 |
fun main() { val list = listOf("A", "B", "C") val separator = "-" val string = list.joinToString(separator) println(string) // A-B-C } |
2. Using String.join() function
Another good solution is to use the join() function of Java’s String class. We can use this as:
|
1 2 3 4 5 6 7 8 |
fun main() { val list = listOf("A", "B", "C") val separator = "-" val string = java.lang.String.join(separator, list) println(string) // A-B-C } |
3. Using StringBuilder
Finally, you can use the StringBuilder to build the string character by character. We can do this by looping over the list and concatenate each character to the StringBuilder instance with the specified delimiter.
To deal with the trailing delimiters characters, you can use the removeSuffix() function before calling returning the StringBuilder as a string.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val list = listOf("A", "B", "C") val separator = "-" val sb = StringBuilder() list.forEach { sb.append(it).append(separator) } val string = sb.removeSuffix(separator).toString() println(string) // A-B-C } |
That’s all about converting a list to a string 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 :)