Working with Strings
Prerequisites: Strings and string templates
Strings come with many useful functions and properties.
Example
fun main() {
val text = " Hello, Kotlin World "
val trimmed = text.trim()
println(trimmed)
println(trimmed.uppercase())
println(trimmed.lowercase())
println(trimmed.length)
println(trimmed.startsWith("Hello"))
println(trimmed.endsWith("!"))
println("Kotlin" in trimmed)
println(trimmed.replace("World", "Friends"))
println("a,b,c".split(","))
println("Kotlin".reversed())
println("Kotlin"[0])
println("Kotlin".substring(1, 4))
println("".isEmpty())
println(" ".isBlank())
println("ruby".replaceFirstChar { it.uppercase() })
}
Expected output
Hello, Kotlin World
HELLO, KOTLIN WORLD
hello, kotlin world
19
true
false
true
Hello, Kotlin Friends
[a, b, c]
niltoK
K
otl
true
true
Ruby
Things to notice:
- Strings are immutable: functions like
uppercase()return a new string and leave the original unchanged. "Kotlin" in trimmedchecks whether one string contains another.- Square brackets get a character by position, starting at
0. substring(1, 4)takes positions 1 up to, but not including, 4.isEmpty()is true only for"";isBlank()is also true for strings of only whitespace — usually what you want for user input.
Looping over characters
fun main() {
for (c in "Hi!") {
println(c)
}
println("banana".count { it == 'a' })
}
H
i
!
3
Common mistakes
- Using
==vs===. In Kotlin,==compares string content, which is what you want. (===checks whether two references point to the same object.) - Reading a position past the end:
"Hi"[5]throwsStringIndexOutOfBoundsException.
Practice
Given val email = " Ada@Example.COM ", print it trimmed and in
lowercase.
Show solution
fun main() {
val email = " Ada@Example.COM "
println(email.trim().lowercase())
}
ada@example.com