In this tutorial, you shall learn how to join a list of strings with a given separator in Kotlin, using List.joinToString() function, with examples.

Kotlin – Join strings with a separator

To join a list of strings with a given separator string in Kotlin, you can use List.joinToString() function.

Call joinToString() function on the list of strings, and pass the separator string as argument to the function.

Syntax

If strings is the given list of strings, then the syntax to join these strings with a specific separator string separator is

</>
Copy
strings.joinToString(separator)

Examples

1. Join list of strings with comma separator string

In the following program, we take a list of strings in strings, and join them using joinToString() function, with ", " as a separator string.

Main.kt

</>
Copy
fun main() {
    val words = listOf("apple", "banana", "cherry")
    val separator = ", "
    val result = words.joinToString(separator)
    println(result)
}

Output

apple, banana, cherry

2. Join strings with transformation to each string

We can also apply a transformation on the individual strings, and then join them, using joinToString() function. To modify each string while joining, pass a lambda function to the joinToString() function.

In the following program, while joining the strings, we convert the string to uppercase, and enclose the string in double quotes.

Main.kt

</>
Copy
fun main() {
    val words = listOf("apple", "banana", "cherry")
    val separator = ", "
    val result = words.joinToString(separator) {
        "\"" + it.uppercase() + "\""
    }
    println(result)
}

Output

"APPLE", "BANANA", "CHERRY"

Conclusion

In this Kotlin Tutorial, we learned how to join a list of strings with a specific separator string using joinToString() function.