Scala String lastIndexof() Method with Example

Here, we will learn about the lastIndexOf() method in Scala. The lastIndexOf() method finds the last occurrence of the given sub-string in Scala. We will see its working, syntax and examples.
Submitted by Shivang Yadav, on January 30, 2021

String is an immutable collection that stores sequences of characters.

String lastIndexOf() Method

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


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.