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() + "...")
}
}
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)
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?
I agree! Thank you for the suggestion!