Concatenate two strings in Kotlin
This article explores different ways to concatenate two strings in Kotlin.
1. Using + Operator
The + operator is one of the widely used approaches to concatenate two strings in Kotlin.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun concat(s1: String, s2: String): String { return s1 + s2 } fun main() { val s1 = "Hello" val s2 = "World" val result = concat(s1, s2) println(result) // HelloWorld } |
Alternatively, you can use the plus() function to concatenate one string at the end of another string.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun concat(s1: String, s2: String): String { return s1.plus(s2) } fun main() { val s1 = "Hello" val s2 = "World" val result = concat(s1, s2) println(result) // HelloWorld } |
2. Using StringBuilder
The recommended way to concatenate two strings in Kotlin is StringBuilder. It is append() function is overloaded to accept different data types.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun concat(s1: String, s2: String): String { return StringBuilder(s1).append(s2).toString() } fun main() { val s1 = "Hello" val s2 = "World" val result = concat(s1, s2) println(result) // HelloWorld } |
You can easily extend the solution for concatenating multiple strings:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
fun concat(vararg string: String): String { val sb = StringBuilder() for (s in string) { sb.append(s) } return sb.toString() } fun main() { val s1 = "Hello" val s2 = " " val s3 = "World" val result = concat(s1, s2, s3) println(result) // Hello World } |
3. Using String Templates
Finally, you can easily concatenate multiple strings using string templates. The String literals may contain template expressions, i.e., pieces of code that are evaluated and whose results are concatenated into the string.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun concat(s1: String, s2: String): String { return "$s1 $s2" } fun main() { val s1 = "Hello" val s2 = "World" val result = concat(s1, s2) println(result) // Hello World } |
4. Using joinToString() function
If you want to concatenate all the list elements with a separator, you can use the joinToString() function.
|
1 2 3 4 5 6 7 |
fun main() { var list = listOf("Hello", "World") val result = list.joinToString("") println(result) // HelloWorld } |
That’s all about concatenating two 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 :)