Library contents

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

  1. Start with "a=b"
  2. Do this Split at the first equals sign
  3. Result Left a, right b
The equals sign marks the boundary between the two fields.

Syntax

Kotlin 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.

From the programfor (field in listOf("token=a=b", "mode=", "broken")) {
First output line[a=b]
Lesson.kt
fun main() {
    for (field in listOf("token=a=b", "mode=", "broken")) {
        if (field.indexOf('=') < 0) println("missing")
        else println("[" + field.substringAfter('=') + "]")
    }
}
Output
[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

Advertisements

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.

Givensource=HDMI2
Worked resultHDMI2

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.

Givenrule=x=y
Worked resultx=y