Kotlin indexOf
Locate the first separator or search term in a plain ASCII record.
A simple example
indexOf
- Start with "aba", looking for b
- Do this Find the first match
- Result Index 1 (zero-based)
fun main() {
val value = "aba"
val other = "b"
println(value.indexOf(other))
}
1
Syntax
value.indexOf(other)
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarLocate the hyphen in a classroom code
A compound filename or route code uses punctuation to separate fields. Decide whether the first or last separator marks the desired boundary before extracting the field next to it.
fun main() {
val value = "CS-104"
val other = "-"
println(value.indexOf(other))
}
2
The hyphen follows the two letters CS.
Find the first separator on a route
A route string contains several stops separated by the same punctuation. Find the first separator to locate the end of the starting stop before the remaining route is processed.
fun main() {
val value = "A/B/C"
val other = "/"
println(value.indexOf(other))
}
1
The first slash comes immediately after A.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Find the dash in this identifier. How many characters precede the matching separator?
What to watch for
Check the language-specific missing-match result before slicing. Byte and character offsets may diverge for Unicode input.