Kotlin program to get the substring after a special character

Introduction :

Our problem is to get the substring after the last occurrence of a special character in a string in Kotlin. For example, if our string is https://www.codevscolor.com, and if we need the substring after the last occurrence of ’/’, it should return www.codevscolor.com.

I will show you two different ways to solve this problem. Drop a comment below if you know any other solution.

Method 1: Using substring :

The substring method is used to get a substring identified by an index. We can call substring with the start index for the substring. To get the last index, method lastIndexOf can be used.

fun main() {
    val givenString = "https://www.codevscolor.com"
    val index = givenString.lastIndexOf('/')
    println("Index of last occurrence : $index")
    
    println(givenString.substring(index+1))
}

If you run this program, it will print the below output :

Index of last occurrence : 7
www.codevscolor.com

The last index of / is 7 and the substring starts from index 8 i.e. from the first w.

If the character is not in that string, lastIndexOf will return -1 and substring will return the complete string.

fun main() {
    val givenString = "https://www.codevscolor.com"
    val index = givenString.lastIndexOf('%')
    println("Index of last occurrence : $index")

    println(givenString.substring(index+1))
}

It will print :

Index of last occurrence : -1
https://www.codevscolor.com

Method 2: Using substringAfterLast :

substringAfterLast is another method that takes one character as the argument and returns the substring after the last occurrence of that character. No need to find the index.

fun main() {
    val givenString = "https://www.codevscolor.com"

    println(givenString.substringAfterLast("/"))
}

It will print :

www.codevscolor.com

Kotlin substring after character