Kotlin String and String Templates

Kotlin String

Strings are a sequence of characters. For example, "Hello there!" is a string literal.

In Kotlin, all strings are objects of String class. Meaning, string literals such as "Hello there!" are implemented as instances of this class. 


How to create a String variable?

Here is how you can define a String variable in Kotlin. For example,

val myString = "Hey there!"

Here, myString is a variable of type String.

You can declare variable of type String and specify its type in one statement, and initialize the variable in another statement later in the program.

val myString: String
... .. ...
myString = "Howdy"

How to access characters of a String?

To access elements (character) of a string, index access operator is used. For example,

val myString = "Hey there!"
val item = myString[2]

Here, item variable contains y, third character of the myString string. It's because indexing in Kotlin starts from 0 not 1.

val myString = "Hey there!"
var item: Char

item = myString[0]    // item contains 'H'
item = myString[9]    // item contains '!'
item = myString[10]   // Error! String index is out of range
item =  myString[-1]  // Error! String index is out of range 

Example: Iterate through a String

If you need to iterate through elements of a string, you can do it easily by using a for loop.

fun main(args: Array<String>) {
    val myString = "Hey!"

    for (item in myString) {
        println(item)
    }
}

When you run the program, the output will be:

H
e
y
!

Strings in Kotlin are Immutable

Like Java, strings are immutable in Kotlin. This means, you cannot change individual character of a string. For example,

var myString = "Hey!"
myString[0] = 'h'      // Error! Strings

However, you can reassign a string variable again if you declared the variable using keyword var. (Recommended Reading: Kotlin var Vs val)

Example: Reassigning a String Variable.


fun main(args: Array<String>) {
    var myString = "Hey!"
    println("myString  = $myString")

    myString = "Hello!"
    println("myString  = $myString")
}

When you run the program, the output will be:

myString  = Hey!
myString  = Hello!

String Literals

A literal is the source code representation of a fixed value. For example, "Hey there!" is a string literal that appears directly in a program without requiring computation (like variables).

There are two types of string literals in Kotlin:

1. Escaped string


A escaped string may have escaped characters in them. For example,

val myString = "Hey there!\n"

Here, \n is an escape character which inserts a newline in the text where it appears.

Here is a list of escape characters supported in Kotlin:

  • \t - Inserts tab
  • \b - Inserts backspace
  • \n - Inserts newline
  • \r - Inserts carriage return
  • \' - Inserts single quote character
  • \" - Inserts double quote character
  • \\ - Inserts backslash
  • \$ - Inserts dollar character

2. Raw String


A raw string can contain newlines (not new line escape character) and arbitrary text. A raw string is delimited by a triple quote """. For example,

fun main(args: Array<String>) {

    val myString = """
    for (character in "Hey!")
        println(character)
"""
    print(myString)
}

When you run the program, the output will be:

    for (character in "Hey!")
        println(character)

You can remove the leading whitespaces of a raw string using trimMargin() function. For example,

Example: Printing Raw String


fun main(args: Array<String>) {

    println("Output without using trimMargin function:")

    val myString = """
    |Kotlin is interesting.
    |Kotlin is sponsored and developed by JetBrains.
"""
    println(myString)

    println("Output using trimMargin function:\n")
    println(myString.trimMargin())
}

When you run the program, the output will be:

Output without using trimMargin function:

    |Kotlin is interesting.
    |Kotlin is sponsored and developed by JetBrains.

Output using trimMargin function:

Kotlin is interesting.
Kotlin is sponsored and developed by JetBrains.

By default, trimMargin() function uses | as margin prefix. However, you can change it by passing a new string to this function.

Example: trimMargin() with Argument


fun main(args: Array<String>) {

    val myString = """
    !!! Kotlin is interesting.
    !!! Kotlin is sponsored and developed by JetBrains.
"""
    println(myString.trimMargin("!!! "))
}

When you run the program, the output will be:

Kotlin is interesting.
Kotlin is sponsored and developed by JetBrains.

Kotlin String Templates

Kotlin has an awesome feature called string templates that allows strings to contain template expressions.

A string template expression starts with a dollar sign $. Here are few examples:

Example: Kotlin String Template


fun main(args: Array<String>) {

    val myInt = 5;
    val myString = "myInt = $myInt"

    println(myString)
}

When you run the program, the output will be:

myInt = 5

It is because the expression $myInt (expression starting with $ sign) inside the string is evaluated and concatenated into the string.

Example: String Template With Raw String


fun main(args: Array<String>) {
    val a = 5
    val b = 6

    val myString = """
    |${if (a > b) a else b}
"""
    println("Larger number is: ${myString.trimMargin()}")
}

When you run the program, the output will be:

Larger number is: 6

Few String Properties and Functions

Since literals in Kotlin are implemented as instances of String class, you can use several methods and properties of this class.

  • length property - returns the length of character sequence of an string.
  • compareTo function - compares this String (object) with the specified object. Returns 0 if the object is equal to the specfied object.
  • get function - returns character at the specified index.
    You can use index access operator instead of get function as index access operator internally calls get function.
  • plus function - returns a new string which is obtained by the concatenation of this string and the string passed to this function.
    You can use + operator instead of plus function as + operator calls plus function under the hood.
  • subSequence Function - returns a new character sequence starting at the specified start and end index.

Example: String Properties and Function


fun main(args: Array<String>) {

    val s1  = "Hey there!"
    val s2 = "Hey there!"
    var result: String

    println("Length of s1 string is ${s1.length}.")

    result = if (s1.compareTo(s2) == 0) "equal" else "not equal"
    println("Strings s1 and s2 are $result.")

    // s1.get(2) is equivalent to s1[2]
    println("Third character is ${s1.get(2)}.")

    result = s1.plus(" How are you?") // result = s1 + " How are you?"
    println("result = $result")

    println("Substring is \"${s1.subSequence(4, 7)}\"")

}

When you run the program, the output is:

Length of s1 string is 10.
Strings s1 and s2 are equal.
Third character is y.
result = Hey there! How are you?
Substring is "the"

Visit Kotlin String class for more information on extension properties, extension, functions and constructors.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges