Many times while programming for Android it is practical to shorten a text, however, many times we don’t want to cut a word in half at the end. That is why I have written this abbreviateString extension method.

fun String.abbreviateString(maxLength:Int,moreIndicator:String="..."):String {
    val words=this.split(' ')
    val result= mutableListOf<String>()
    var totalLength=0

    for(word in words) {
        if (totalLength<=maxLength) {
            result.add(word)
            totalLength += word.length
        } else {
            break
        }

    }
    if (words.size>=result.size) {
        result.add(moreIndicator)
    }

    return result.joinToString(" ")
}