DEV Community

Cover image for How to truncate strings in Kotlin?

How to truncate strings in Kotlin?

michaelgrigoryan25 profile image Michael Grigoryan ・1 min read

When we have large strings and when we don't want to show the full content of it, we'll have to use what's called String Truncation.

Basically, let's say we have this string:
Lorem ipsum dolor sit amet, consectetur adipiscing elit

And we only want to return the first 18 characters. To do that I have written a simple function.

fun truncateString(string: String, maxChar: Int): String {
    return if (string.length < maxChar) {
    } else {
        ((string.subSequence(0, maxChar)).toString() + "...")
Enter fullscreen mode Exit fullscreen mode

Basically, we are taking a string input from our user and an integer which will limit the characters in the string.
So, in this case we'll to truncateString(thatString, 18) and it'll return Lorem ipsum dolor .... As easy as that!

I hope you liked this small but really useful function!

Discussion (2)

Editor guide
douglascf profile image
Douglas Fornaro

Very nice!
Would be nice to create an extension function from String and also give the opportunity to change the "..." to "View more..." for exemple... What do you think?

michaelgrigoryan25 profile image
Michael Grigoryan Author

I agree! Thank you for the suggestion!