Kotlin Tutorial · Kotlin Basics · Lesson 6 of 31
Kotlin Strings
Work with strings: templates, common functions, multiline raw strings and building strings efficiently.
Common string functions
Strings are immutable; every function returns a new string.
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.
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?
Removes all spacesRemoves the common leading indentation from every lineTrims only the last lineConverts tabs to spaces
Show answer
Answer: Removes the common leading indentation from every line