- Kotlin - Home
- Kotlin - Overview
- Kotlin - Environment Setup
- Kotlin - Architecture
- Kotlin - Basic Syntax
- Kotlin - Comments
- Kotlin - Keywords
- Kotlin - Variables
- Kotlin - Data Types
- Kotlin - Operators
- Kotlin - Booleans
- Kotlin - Strings
- Kotlin - Arrays
- Kotlin - Ranges
- Kotlin - Functions
- Kotlin Control Flow
- Kotlin - Control Flow
- Kotlin - if...Else Expression
- Kotlin - When Expression
- Kotlin - For Loop
- Kotlin - While Loop
- Kotlin - Break and Continue
- Kotlin Collections
- Kotlin - Collections
- Kotlin - Lists
- Kotlin - Sets
- Kotlin - Maps
- Kotlin Objects and Classes
- Kotlin - Class and Objects
- Kotlin - Constructors
- Kotlin - Inheritance
- Kotlin - Abstract Classes
- Kotlin - Interface
- Kotlin - Visibility Control
- Kotlin - Extension
- Kotlin - Data Classes
- Kotlin - Sealed Class
- Kotlin - Generics
- Kotlin - Delegation
- Kotlin - Destructuring Declarations
- Kotlin - Exception Handling
Kotlin String - indexOfLast() Function
The Kotlin string indexOfLast() function is used to return index of the last character matching the given predicate, or -1 if the char sequence does not contain such character.
This function provides a simple way to perform reverse conditional search operations for many use cases, including string validation, substring extraction, and data analysis.
Syntax
Following is the syntax of the Kotlin string indexOfLast() function −
fun CharSequence.indexOfLast( predicate: (Char) -> Boolean ): Int
Parameters
This function accepts a predicate representing the lambda function that defines the condition to match. It is applied to each character in the string until the condition is satisfied.
Return value
This function returns an index of the last character matching the predicate, or -1 if the string does not contain such a character.
Example 1: Get the Index of Last Char
Following is the basic example, we use indexOfLast() to get the index of the last char matching the predicate in kotlin −
fun main() {
val str = "This is kotlin"
val index = str.indexOfLast { it in "aeiou" }
println("Index of the last vowel: $index")
}
Output
Following is the output −
Index of the last vowel: 12
Example 2: Get the Index of Last Digit
Now, let's look at another example of the indexOfLast() to get the index of the last digit in the string −
fun main() {
val str = "Hello, sector136"
val index = str.indexOfLast { it.isDigit() }
println("Index of last Digit: $index")
}
Output
Following is the output −
Index of last Digit: 15
Example 3: Get the Index of the Last Uppercase
In this example, we display the index of the last uppercase letter using the indexOfLast() in Kotlin −
fun main() {
val str = "hello TutorialsPoint"
val index = str.indexOfLast { it.isUpperCase() }
println("Index of last uppercase: $index")
}
Output
Following is the output −
Index of last uppercase: 15