How to concatenate Strings in Kotlin - Kotlin String Examples

Published October 06, 2021


In this kotlin string example we will learn what is String and how to concatenate strings in kotlin. String data type, string literals and string templates.

What is Sting in Kotlin?

Similar to other programming languages in kotlin, String is a series of characters. Let's check the below code, how to create string variable in kotlin

fun main() {
    val helloWorld = "Hello Kotlin !!"
    val helloWorld2 : String = "Hello Kotlin !!"
    print(helloWorld)
}

 

How to read characters from Kotlin String

Similar to other programming languages in kotlin we can read characters from string with their index position

fun main() {
    val helloKotlin = "Hello Kotlin !!"
    val helloKotlin2 : String = "Hello Kotlin !!"
    println(helloKotlin[6])
    println(helloKotlin[7])
    println(helloKotlin[8])
    println(helloKotlin[9])
    println(helloKotlin[10])
}

 

 

Output:

K

o

t

l

i

 

Concatenate String in Kotlin

String in kotlin is Immutable, We can concatenate two strings in kotlin by '+' . It will create new string on concatenate

fun main()
{
    val kotlinstring1 = "Kotlin String1 "
    val kotlinstring2 = "Kotlin String2 "
    val kotlinstring = kotlinstring1 + kotlinstring2

    println(kotlinstring)

}

 

Output:

Kotlin String1 Kotlin String2

 

 

Kotlin literals, Kotlin has two types of string literals

  • Escaped string
  • Raw string

An escaped string contains one escaped character in it

 

String literal examples are  \t, \b, \n, \r,

 

Concatenate String by string template

We can also concatenate string by

fun main() {
    val count = 10
   val countStirng = "count $count"
    print(countStirng)
}

 

Output:

count 10

 

Conclusion: In this Kotlin string example we covered what is String and How to concatenate string in kotlin.

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

13 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions