Skip to main content

How to truncate a string to a specific length in Kotlin

How to truncate a string to a specific length in Kotlin.

Here's a step-by-step tutorial on how to truncate a string to a specific length in Kotlin:

  1. Start by defining a function that takes two parameters: the original string and the desired length of the truncated string. For example:
fun truncateString(original: String, length: Int): String {
// implementation goes here
}
  1. Inside the function, check if the length of the original string is already less than or equal to the desired length. If it is, simply return the original string as it is. This step is important to avoid unnecessary truncation when the original string is already shorter than the desired length. For example:
if (original.length <= length) {
return original
}
  1. If the original string is longer than the desired length, use the substring function to extract a substring from the original string starting from index 0 and ending at the desired length minus 3. This is to account for the ellipsis that will be added to indicate truncation. For example:
val truncated = original.substring(0, length - 3)
  1. Finally, append an ellipsis (...) to the truncated string to indicate that it has been truncated. This can be done using the plus operator (+). For example:
return truncated + "..."

Putting it all together, the complete function would look like this:

fun truncateString(original: String, length: Int): String {
if (original.length <= length) {
return original
}

val truncated = original.substring(0, length - 3)
return truncated + "..."
}

Here's an example usage of the truncateString function:

val originalString = "This is a long string that needs to be truncated."
val truncatedString = truncateString(originalString, 20)
println(truncatedString) // Output: "This is a long string..."

In this example, the original string is truncated to a length of 20 characters and the result is printed.

That's it! You now have a function that can truncate a string to a specific length in Kotlin. Feel free to use this function in your Kotlin projects whenever you need to truncate strings.