Home »
Scala
Scala String lastIndexof() Method
By IncludeHelp Last updated : October 21, 2024
Description and Usage
The lastIndexOf() method is used to get the index of the last occurrence of the sub-string which is passed as parameter to the method in the calling string.
Syntax
string_Name.lastIndexOf(search_subString)
Parameters
The method accepts a single parameter of type string. It is the substring whose occurrence is to be found.
Return Value
It returns an integer value which is the index of last occurrence of the substring in the string.
Example 1: When there's only one occurrence of the substring
object MyClass {
def main(args: Array[String]) {
val myString = "includehelp"
println("The string is '" + myString + "'")
val lastIndex = myString.lastIndexOf("help")
println("The last index of 'help' is " + lastIndex )
}
}
Output
The string is 'includehelp'
The last index of 'help' is 7
Example 2: When there are multiple occurrences of the substring
object MyClass {
def main(args: Array[String]) {
val myString = "abaabcdfssabsa"
println("The string is '" + myString + "'")
val lastIndex = myString.lastIndexOf("ab")
println("The last index of 'ab' is " + lastIndex )
}
}
Output
The string is 'abaabcdfssabsa'
The last index of 'ab' is 10
Example 3: When there is no occurrence of substring
object MyClass {
def main(args: Array[String]) {
val myString = "scala Programming Language"
println("The string is '" + myString + "'")
val lastIndex = myString.lastIndexOf("include")
println("The last index of 'include' is " + lastIndex )
}
}
Output
The string is 'scala Programming Language'
The last index of 'include' is -1