Concatenate multiple strings in Kotlin
This article explores different ways to concatenate multiple strings in Kotlin
1. Using joinToString() function
In Kotlin, the recommended way for concatenating multiple strings is using the joinToString() function with empty string as separator.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun concatenate(vararg string: String?): String { return string.joinToString("") } fun main() { val s1 = "Hello" val s2 = "World" val string = concatenate(s1, s2) println(string) // HelloWorld } |
2. Using StringBuilder
Another way to concatenate multiple strings is to create a StringBuilder instance and append each string to it using the append() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun concatenate(vararg string: String?): String { var sb = StringBuilder() string.forEach { sb.append(it) } return sb.toString() } fun main() { val s1 = "Hello" val s2 = "World" val string = concatenate(s1, s2) println(string) // HelloWorld } |
3. Using plus operator
Kotlin also has the + operator or plus() function, often used to concatenate strings to an existing string. The idea is to loop through the varargs and append each element to a string. It should be best avoided when the total number of the string is more.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun concatenate(vararg string: String?): String { var result = "" string.forEach { result = result.plus(it) } return result } fun main() { val s1 = "Hello" val s2 = "World" val string = concatenate(s1, s2) println(string) // HelloWorld } |
That’s all about concatenating multiple strings 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 :)