Kotlin Tutorial · Kotlin Basics · Lesson 6 of 31

Kotlin Strings

Work with strings: templates, common functions, multiline raw strings and building strings efficiently.

Create a free account to save this page, take notes and track your progress. Sign in

Common string functions

Strings are immutable; every function returns a new string.

String functions
fun main() {
    val email = "  [email protected] "
    val clean = email.trim().lowercase()
    println(clean)
    println(clean.length)
    println(clean.substringBefore("@"))
    println(clean.endsWith(".com"))
    println(clean.replace("example", "test"))
    println("a,b,,c".split(","))
    println("ab".repeat(3))
}

Output

[email protected]
21
ana.silva
true
[email protected]
[a, b, , c]
ababab

Run this on your computer — see “Get Started” for setup.

Raw strings and buildString

Triple-quoted raw strings keep line breaks and don't process escapes; trimIndent() removes the common indentation. buildString { } builds text efficiently with a StringBuilder.

Raw strings and buildString
fun main() {
    val name = "Ana"
    val letter = """
        Dear $name,
        Your order has shipped.
    """.trimIndent()
    println(letter)

    val table = buildString {
        for (i in 1..3) {
            append("row ")
            appendLine(i)
        }
    }
    print(table)
}

Output

Dear Ana,
Your order has shipped.
row 1
row 2
row 3

Run this on your computer — see “Get Started” for setup.

Test yourself

What does trimIndent() do to a raw string?

  1. Removes all spaces
  2. Removes the common leading indentation from every line
  3. Trims only the last line
  4. Converts tabs to spaces
Show answer

Answer: Removes the common leading indentation from every line

Was this page helpful?