ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

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
ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.