split and replace
- Kotlin course
- Beginner
- Lesson 34/116
- 5 min
Learn string processing with split and replace.
split and replace
split(delimiter) splits a String at the given delimiter and returns a List<String>. replace(old, new) swaps a piece with a new one.
val parts = "a,b,c".split(",")
println(parts) // [a, b, c]
val fixed = "cat".replace("a", "o")
println(fixed) // cotThe result of split is a list; each item is a separate String. replace changes all matches, not just the first.
Neither method mutates the original String; both return a new value.
Practice Use split and replace
Write a fun main(). Assign "apple,bread" (with a comma) to val items. Print items.split(",") for the split list and items.replace("e", "E") for the swapped string on separate lines.
Starter code
fun main() {
// Split and swap
}Sample solution
fun main() {
val items = "apple,bread"
println(items.split(","))
println(items.replace("e", "E"))
}Expected output
[apple, bread] applE,brEad
replace and chaining
replace can also be chained. To make several swaps in order, call the methods back to back.
val s = "a-b-c"
val r = s.replace("-", " ").replace("a", "A")
println(r) // A b cFirst dashes become spaces, then a becomes A. Since each replace returns a new String, chaining works.
Order matters: replace("a", "A").replace("-", " ") makes a different intermediate value but the same result here.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the methods
| Term | Meaning |
|---|---|
split(",") |
Splits at comma |
replace("a", "e") |
Turns a to e |
split(" ") |
Splits at space |
parts[0] |
First item |
2 What does "a,b,c".split(",") return?
- A String
- A list of three Strings Correct answer
- Three chars
- Error
Explanation: split returns a List<String>; here it has three items.
3 Complete the replace call
val fixed = s.____("a", "e")
val fixed = s.replace("a", "e")
Explanation: s.replace("a", "e") turns all a's into e's.