Kotlin Strings
A String is a sequence of characters. Strings are everywhere — names, messages, file contents — so Kotlin gives them a rich set of properties and functions. Kotlin strings are immutable: functions like uppercase() return a new string and leave the original unchanged.
Creating strings
fun main() {
val first = "Grace"
val last = "Hopper"
val full = "$first $last"
println(full)
println("Length: ${full.length}")
println("First letter: ${full[0]}")
println("Last letter: ${full.last()}")
}Grace Hopper
Length: 12
First letter: G
Last letter: r
Characters are accessed by index, starting at 0. full[0] is a Char.
Common functions
| Function | Example | Result |
|---|---|---|
uppercase() / lowercase() |
"Hi".uppercase() |
"HI" |
trim() |
" hi ".trim() |
"hi" |
contains(x) |
"kotlin".contains("tl") |
true |
startsWith(x) / endsWith(x) |
"file.kt".endsWith(".kt") |
true |
indexOf(x) |
"banana".indexOf("n") |
2 |
substring(a, b) |
"kotlin".substring(0, 3) |
"kot" |
replace(a, b) |
"a-b".replace("-", "+") |
"a+b" |
split(x) |
"a,b".split(",") |
[a, b] |
repeat(n) |
"ab".repeat(3) |
"ababab" |
reversed() |
"abc".reversed() |
"cba" |
isEmpty() / isBlank() |
" ".isBlank() |
true |
fun main() {
val raw = " Kotlin is Concise "
val text = raw.trim()
println(text.uppercase())
println(text.lowercase())
println(text.contains("concise", ignoreCase = true))
println(text.indexOf("is"))
println(text.substring(10))
println(text.replace("Concise", "Fun"))
}KOTLIN IS CONCISE
kotlin is concise
true
7
Concise
Kotlin is Fun
Comparing strings
Use == to compare contents. For case-insensitive comparison, pass ignoreCase = true to equals. compareTo tells you the alphabetical order (negative, zero or positive).
fun main() {
val a = "Apple"
val b = "apple"
println(a == b)
println(a.equals(b, ignoreCase = true))
println("cat".compareTo("dog") < 0)
}false
true
true
Splitting and joining
split breaks a string into a list; joinToString builds a string from a collection.
fun main() {
val csv = "milk,eggs,bread"
val items = csv.split(",")
println(items)
println(items.size)
println(items.joinToString(" | "))
println(items.joinToString(prefix = "[", postfix = "]") { it.uppercase() })
}[milk, eggs, bread]
3
milk | eggs | bread
[MILK, EGGS, BREAD]
Looping over characters
A string can be used in a for loop, one Char at a time:
fun main() {
var vowels = 0
for (ch in "programming") {
if (ch in "aeiou") vowels++
}
println("Vowels: $vowels")
}Vowels: 3
Building strings efficiently
Because strings are immutable, adding to a string in a loop creates many temporary objects. buildString gives you a mutable StringBuilder and returns the finished string:
val stars = buildString {
for (i in 1..3) append("*".repeat(i)).append('\n')
}Tip: Raw strings (
"""...""") are perfect for multi-line text and regular expressions, because backslashes don't need escaping. String templates and formatting get their own chapter in the Idioms section.
Test yourself
What does "Kotlin"[1] return?
- 'K'
- 'o'
- "o"
- An error
After val s = "hi"; s.uppercase(), what is s?
- "HI"
- "hi"
- "Hi"
- null
Which function turns a list into a single string with a separator?
- split
- concat
- joinToString
- toString(sep)