Summary - Advanced strings
- Kotlin course
- Beginner
- Lesson 93/116
- 5 min
Combine Regex, StringBuilder and trim to write a CSV parser.
Summary - Advanced strings
In this group you learned regular expressions, matching with matches and find, transforming with replace, efficient joining with StringBuilder and edge shaping with trim/padStart.
Now it is time to combine them in a single task: find the digits in a text, trim the spaces and print the result. This is a small sample of a real text-processing pipeline.
Practice Clean text and replace digits
First trim the string " a1b22 " to remove edge spaces. Then replace the digits with Regex("\\d+") using "#" and print.
Starter code
fun main() {
val r = Regex("\\d+")
// First trim, then replace digits with diyez, print
}Sample solution
val r = Regex("\\d+")
println(" a1b22 ".trim().replace(r, "#"))Expected output
a#b#
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match tool to purpose
| Term | Meaning |
|---|---|
Regex |
Pattern match |
find |
First match |
replace |
Substitute |
trim |
Edge cleanup |
2 Fill in the blank: builder to string
val sb = StringBuilder("hi")
val s = sb.____()
val sb = StringBuilder("hi")
val s = sb.toString()
Explanation: toString returns the builder's content as a string.
3 You concatenate 500 times in a loop. Which is best?
- StringBuilder Correct answer
- Regex
- String +
- trim
Explanation: Is StringBuilder; it does not create a new object per append.