Library contents

Scala String.lastIndexOf

Find the final separator when a label contains several parts.

A simple example

String.lastIndexOf

  1. Start with "aba", looking for a
  2. Do this Find the last match
  3. Result Index 2 (zero-based)
There are two matches. Searching from the right reaches the final a first.
Lesson.scala
object Lesson {
    def main(args: Array[String]): Unit = {
        val value = "aba"
        val other = "a"
        println(value.lastIndexOf(other))
    }
}
Output
2

Syntax

Scala syntax
value.lastIndexOf(other)
Run these examples in Scala

Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.

scalac Lesson.scala
scala Lesson

Find the final dot in an archive name

An archive name contains more than one period. Locate the final one before extracting the extension so the earlier punctuation in the basename is preserved.

From the programval value = "may.bill.pdf"
Result8
Lesson.scala
object Lesson {
    def main(args: Array[String]): Unit = {
        val value = "may.bill.pdf"
        val other = "."
        println(value.lastIndexOf(other))
    }
}
Output
8

The dot before pdf is the last match.

Advertisements

Find the last route separator

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.

From the programval value = "A/B/C"
Result3
Lesson.scala
object Lesson {
    def main(args: Array[String]): Unit = {
        val value = "A/B/C"
        val other = "/"
        println(value.lastIndexOf(other))
    }
}
Output
3

The final slash comes before stop C.

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?

GivenNC-17
Worked result2

What to watch for

These examples use ASCII. Verify offset units and missing-match behaviour before indexing another string.

Documentation for String.lastIndexOf