DEV Community

loading...
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) {
        string
    } 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 (4)

pic
Editor guide
Collapse
julienhelios profile image
julien-helios • Edited
fun truncateString(string: String, maxChar: Int): String {
    return if (string.length < maxChar) {
        string
    } else {
        string.substring(0, maxChar) + "..."
    }
}
Enter fullscreen mode Exit fullscreen mode

Use substring instead of subSequence to have the result directly in String

Collapse
michaelgrigoryan25 profile image
Michael Grigoryan Author

That seems nicer, I'll use it that way from now on

Collapse
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?

Collapse
michaelgrigoryan25 profile image
Michael Grigoryan Author

I agree! Thank you for the suggestion!