Skip to content

Kotlin join strings with separator

  • by
Kotlin join string with separator

1. Overview

In this article, we will learn to join the Kotlin strings together with a separator. To learn more about other Kotlin topics, you can refer to these articles.

2. Kotlin joinToString

The joinToString function creates a string from all the elements separated using a separator and using the provided prefix and postfix if available.

2.1. Kotlin join byte value of strings example

You can combine byte arrays using the joinToString function.

For example, the following code converts the "Hello" to byte array and combines them using the separator colon :.

fun main() {
    val charset = Charsets.UTF_8
    val byteArray = "Hello".toByteArray(charset) 
    println(byteArray.joinToString(":"))
}

2.3. Join Koilin strings with a separator example

You can also join a collection of objects using the joinToString method.

fun main() {
    val vowels_list: List<String> = listOf("a", "e", "i", "o", "u")
    println(vowels_list.joinToString(separator = "#"))
}

2.4. Add prefix and postfix to the result

You can add a prefix or postfix to the result of the joinToString function:

fun main() {
    val vowels = listOf("a", "e", "i", "o", "u")
    println(vowels.joinToString(separator = "&", prefix = "[", postfix = "]")) 

}

2.5. Truncate result

If the collection of input elements could be huge, you can specify a limit that should be non-negative, in which case only the first limit elements will be appended, followed by the truncated string (which defaults to “…”).

For example, the following chars array is huge and so we are setting the limit as 5 so only the first five elements would be appended, followed by the provided truncated value "…!".

Note that we also converted the elements to the upper case before appending them.

fun main() {
   val chars = charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q')
   println(chars.joinToString(limit = 5, truncated = "...!") { 
       it.uppercaseChar().toString() 
   }) 
}

If you don’t specify the truncated value, then the default value ... is used.

Look at the following example with the default truncated value.

fun main() {
   val chars = charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q')
   println(chars.joinToString(limit = 5) { 
       it.uppercaseChar().toString() 
   }) 
}

3. Conclusion

To sum up, we have learned the Kotlin join strings with a separator. You can find our code samples in our GitHub repository.

Leave a Reply

Your email address will not be published. Required fields are marked *