Kotlin String Concatenation
To concatenate strings in Kotlin, you can use concatenation operator +
. You may usually encounter concatenation operator as addition operator.
Since strings are very commonly used datatypes in business logic, sometimes, you may need to concatenate two or more strings.
In this tutorial, we will learn how to concatenate strings in Kotlin programming language.
Syntax
The syntax to concatenate two strings is given below.
string_1 + string_2
The operator +
concatenates the two operands string1
and string2
and returns the resulting string. You may store the result in a variable.
Concatenation Operator allows chaining. This results in an easy way where you can concatenate two or more strings in a single statement as shown in the following.
string_1 + string_2 + string_3 + ... + stringN
Examples
1. Concatenate strings using String Concatenation Operator
In this example, we shall take two strings string1
and string2
,and concatenate them using String Concatenation Operator.
Kotlin Program
/**
* Kotlin - String Concatenation
*/
fun main(args: Array<String>) {
//a string
var string1 = "https://"
//another string
var string2 = "www.tutorialkart.com"
//concatenate strings
var stringResult = string1 + string2
print(stringResult)
}
Output
https://www.tutorialkart.com
The original strings are unaffected by this concatenation operation.
2. Concatenate more than two strings
You can concatenate more than two strings in a single statement.
In this example, we shall take three strings and perform string concatenation on them. The process should be same for any number of string you would like concatenate.
Kotlin Program
/**
* Kotlin - String Concatenation
*/
fun main(args: Array<String>) {
//a string
var string1 = "https://"
//another string
var string2 = "www.tutorialkart.com"
//yet another string
var string3 = "/kotlin-tutorial/"
//concatenate strings
var stringResult = string1 + string2 + string3
print(stringResult)
}
Output
https://www.tutorialkart.com/kotlin-tutorial/
The order in which the strings are concatenated is determined by the order in which we provide the operands to the concatenation operator.
Conclusion
In this Kotlin Tutorial, we learned how to concatenate strings in Kotlin using String concatenation operator.