Kotlin — Splitting strings and destructuring
Kotlin can split a setting at the first equals sign with a limit of two. Check the number of parts before destructuring them into a key and a value.
A simple example
Split one line of text
- Start with "a=b"
- Do this Separate at =
- Result b
fun main() {
val parts = "a=b".split("=")
println(parts[1])
}
b
Split one setting into a key and a value
split with a limit of two keeps extra equals signs in the second component. Destructuring assigns names to both parts after the size check.
A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.
Run the example
Kotlin/JVM. Run these commands from the directory containing the example.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
fun main() {
val parts = " city = Lima ".split('=', limit = 2)
if (parts.size == 2) {
val (key, value) = parts
println(key.trim() + "=" + value.trim())
}
}
city=Lima
The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.
Try it yourself
What should city = A=B produce?
Check your answer
The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.