Kotlin substringAfter and indexOf
substringAfter returns the suffix after the first delimiter. indexOf can first determine whether the delimiter exists.
A simple example
substringAfter and indexOf
- Start with "a=b"
- Do this Split at the first equals sign
- Result Left a, right b
Syntax
text.substringAfter('=')
Run this example in Kotlin
Save the program as Lesson.kt. Use Kotlin 2.2 on the JVM.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jar
Separate a missing field from an empty value
An import can contain a blank record, an empty field or a missing field. Check how the reader represents each case so a user's deliberate blank is not mistaken for the end of the data.
fun main() {
for (field in listOf("token=a=b", "mode=", "broken")) {
if (field.indexOf('=') < 0) println("missing")
else println("[" + field.substringAfter('=') + "]")
}
}
[a=b] [] missing
The default missing-delimiter result is the original string. Testing the delimiter explicitly preserves the distinction between a malformed field and a present but empty value.
Kotlin documentation for substringAfter and indexOf
Read a projector setting
A teacher saves a projector source in a configuration line. The first equals sign separates the key from its value. Keep the entire suffix, including any later equals sign.
Preserve a calibration formula
A lab note stores a comparison as the value of a setting. The first equals sign separates the key from its value. Keep the entire suffix, including any later equals sign.