String concatenation is joining two or more strings together. In this guide, we will see three ways to concatenate strings in Kotlin.
1. String templates
One of the simplest way of concatenating strings is by using String templates.
fun main(args: Array<String>) { val str1 = "hello" val str2 = "hi" val str3 = "bye" // string interpolation val str4 = "$str1 $str2 $str3" // displaying concatenated string println(str4) }
Output:
hello hi bye
Note: We have space in between the strings because we have given the space while using string template in str4.
2. String concatenation using Plus (+) Arithmetic Operator
We have seen in the Kotlin Operators tutorial that + arithmetic operator is used for addition. The same operator can also be used for string concatenation as shown in the example below. The + operator is translated into a plus() function.
fun main(args: Array<String>) { val str1 = "hello" val str2 = "hi" val str3 = "bye" // joining using + operator // can also be written like this: // val str4 = str1.plus(str2).plus(str3) val str4 = str1 + str2 + str3 // displaying concatenated string println(str4) }
Output:
hellohibye
3. Concatenation using StringBuilder
We can join strings using StringBuilder and then assign it to string by using a toString() function on the StringBuilder object.
fun main(args: Array<String>) { val str1 = "hello" val str2 = "hi" val str3 = "bye" // Obtaining StringBhuilder Object val sb = StringBuilder() //joining strings sb.append(str1).append(str2).append(str3) // StringBuilder to String val str4 = sb.toString() //displaying final string println(str4) }
Leave a Reply