A String is a piece of text, such as a name, a message or a URL. Strings are used in almost every program, so Kotlin gives you many handy functions for working with them.
Page Contents
Creating strings
fun main() {
val name = "Asha"
val empty = ""
val greeting = "Hello, " + name // joining with +
println(greeting)
println(empty.isEmpty())
}Output:
Hello, Asha true
Strings are immutable: functions like uppercase() return a new string and leave the original unchanged.
String templates
Instead of joining strings with +, put variables straight into the text with $. For an expression, use ${ }:
fun main() {
val name = "Ravi"
val items = 3
val price = 49.5
println("Hi $name!")
println("You have $items items")
println("Total: ${items * price}")
println("Name has ${name.length} letters")
}Output:
Hi Ravi! You have 3 items Total: 148.5 Name has 4 letters
To print a real dollar sign, write \$, for example "Price: \$5".
Length and characters
fun main() {
val word = "Kotlin"
println(word.length)
println(word[0]) // first character
println(word.last()) // last character
for (ch in word) print("$ch ")
println()
}Output:
6 K n K o t l i n
Indexes start at 0, so word[0] is the first character. word[10] would crash with StringIndexOutOfBoundsException.
Common string functions
fun main() {
val text = " Learn Kotlin Step by Step "
val t = text.trim()
println(t) // remove spaces at both ends
println(t.uppercase())
println(t.lowercase())
println(t.contains("Kotlin"))
println(t.startsWith("Learn"))
println(t.indexOf("Step"))
println(t.replace("Step", "step"))
println(t.substring(6, 12)) // from index 6 up to (not including) 12
println(t.split(" "))
}Output:
Learn Kotlin Step by Step LEARN KOTLIN STEP BY STEP learn kotlin step by step true true 13 Learn Kotlin step by step Kotlin [Learn, Kotlin, Step, by, Step]
Comparing strings
fun main() {
val a = "kotlin"
val b = "Kotlin"
println(a == b) // compares the text
println(a.equals(b, ignoreCase = true))
println(a.compareTo("java") > 0) // alphabetical order
}Output:
false true true
In Kotlin, == compares the contents of two strings. (In Java, you’d need .equals().)
Checking for empty or blank
fun main() {
val s1 = ""
val s2 = " "
println(s1.isEmpty()) // no characters
println(s2.isEmpty())
println(s2.isBlank()) // only spaces
}Output:
true false true
Use isBlank() to check form input. A user who types only spaces hasn’t really entered anything.
Multiline (raw) strings
Use triple quotes for text over several lines. trimIndent() removes the common indentation:
fun main() {
val message = """
Dear user,
Your order has shipped.
Thanks!
""".trimIndent()
println(message)
}Output:
Dear user, Your order has shipped. Thanks!
Raw strings don’t need escape characters, which makes them handy for JSON or regular expressions.
Escape characters
| Escape | Meaning |
|---|---|
\n | new line |
\t | tab |
\" | double quote |
\\ | backslash |
\$ | dollar sign |
Building strings in a loop: StringBuilder
Because strings are immutable, adding to a string in a long loop creates many temporary strings. Use buildString instead:
fun main() {
val table = buildString {
for (i in 1..5) {
append("5 x $i = ${5 * i}\n")
}
}
print(table)
}Output:
5 x 1 = 5 5 x 2 = 10 5 x 3 = 15 5 x 4 = 20 5 x 5 = 25
Common mistakes
- Expecting a function to change the string:
name.uppercase()alone does nothing visible. Use the result:val upper = name.uppercase(). - Index out of range: check
lengthbefore using[index]orsubstring. - Forgetting the braces:
"$user.name"prints the wholeuserfollowed by “.name”. Write"${user.name}".
Exercise
Take a sentence, count its words, and print it with each word capitalized.
fun main() {
val sentence = "kotlin makes android development fun"
val words = sentence.split(" ")
println("Words: ${words.size}")
println(words.joinToString(" ") { it.replaceFirstChar { c -> c.uppercase() } })
}Output:
Words: 5 Kotlin Makes Android Development Fun
FAQ
How do I concatenate strings in Kotlin?
Use a string template, "$first $last", or the + operator. Templates are usually easier to read.
Are Kotlin strings mutable?
No. Every change returns a new string. Use buildString or StringBuilder when you build text step by step.
How do I compare two strings ignoring case?
a.equals(b, ignoreCase = true).
