Method to Get last n Characters of String in Kotlin

In this article, you will find a very simple method that will help you to get the last n (1, 2, 3, 4, …) characters from a String in Kotlin. This method is simple, it will just take String and Integer count as a parameter and returns another string containing the last specified number of characters.  In this article, we will discuss the method to get the last characters in Kotlin. The Kotlin function is the following.

Get last n characters of String in Kotlin

Method to Get Last n Character in Kotlin

fun getLastNCharsOfString(str: String, n: Int): String? {
        var lastnChars = str
        if (lastnChars.length > n) {
            lastnChars = lastnChars.substring(lastnChars.length - n, lastnChars.length)
        }
        return lastnChars
    }

Input Function

getLastNCharsOfString("Hello world", 3);

Return Value (Output)

"rld"

Now you can see the output of the above code. As you saw that the 1st parameter is “Hello world” and the 2nd parameter pass is “3” which means that from the n character of the string last 3 parameters will display in the output.

How it Works

This method will take a String and an Integer as a parameter. After that, it will check the count of string to avoid index out of bounds exception. If the Integer n value is greater than the total length of the String then it will use the subString method to get the last specified character from the string.

That’s It. This is how to Get last n characters of String in Kotlin

If you have any questions feel free to ask in the comments section below.

Next Article

Find Distance Between Two Locations in Kotlin

Please share this post:
Posts created 31

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: