Kotlin String Operations
String operations cut a string into pieces and pull chosen pieces out of it. Each operation returns a new value and leaves the original string unchanged.
Splitting a string into pieces
The call split() cuts the string at each comma. The result is a list, so its size and its parts can be read like any list.
fun main() {
val line = "apples,pears,plums,figs"
val parts = line.split(",")
println(parts)
println(parts.size)
println(parts[1])
}Splitting with a limit
A limit of 3 stops the cutting after two cuts. The third piece keeps the rest of the string whole.
fun main() {
val text = "one-two-three-four"
val parts = text.split("-", limit = 3)
println(parts)
println(parts[2])
}Taking text before and after a mark
The call substringBefore() keeps the text before the first mark. The call substringAfter() keeps the text after it.
fun main() {
val email = "ada@example.com"
println(email.substringBefore("@"))
println(email.substringAfter("@"))
println("readme".substringAfter("."))
}Copying a range and trimming the ends
The call substring() with a range copies both end characters of the range. The calls removePrefix() and removeSuffix() drop a piece only when it sits at that end.
fun main() {
val code = "KT-4821-INT"
println(code.substring(3..6))
val file = "temp-report.txt"
println(file.removePrefix("temp-"))
println(file.removePrefix("temp-").removeSuffix(".txt"))
}A split and join round trip
Splitting a string and joining the pieces rebuilds a string. A different separator gives the same words in a new shape.
fun main() {
val words = "the quick brown fox"
val parts = words.split(" ")
println(parts)
println(parts.joinToString(" "))
println(parts.joinToString("-"))
}Example
fun main() {
val address = "Ada Lovelace, 12 Analytical Lane, London"
val parts = address.split(", ")
println(parts)
println(address.substringBefore(","))
println(address.substringAfter(", "))
println(parts.joinToString(" / "))
}Key points
- Use split() to cut a string at a delimiter and get a list of the pieces.
- Give split() a limit to cap the number of pieces, and the last piece keeps the rest of the string.
- Use substringAfter() to take the text after the first match of a delimiter.
- Use substringBefore() to take the text before the first match of a delimiter.
- Use substring() with a range to copy the characters inside that range.
- Use removePrefix() and removeSuffix() to drop a known piece from one end of a string.
In this example one address line is cut in several ways. Split gives the three parts as a list, substringBefore() isolates the name, substringAfter() keeps everything past the first comma, and joinToString() rebuilds the line with a new separator.
Note
When a delimiter is missing, substringAfter() and substringBefore() return the whole string.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
A program splits "red,green,blue" on "," with a limit of 2. What does printing the resulting list show?