Kotlin String - trimEnd() Function



The Kotlin string trimEnd() function is used to return a subsequence of the original character sequence (original string) with the trailing character removed based on the specific criteria. This includes:

  • Removing trailing characters based on the predicate.
  • Removing trailing characters from a char array.
  • Removing trailing white-space.
This function removes trailing special characters or trailing white-space, but not the middle, character sequence.

Syntax

Following is the syntax of the Kotlin string trimEnd() function −

// default trimEnd
fun String.trimEnd(): String

// trimEnd with predicate
fun CharSequence.trimEnd(predicate: (Char) -> Boolean): CharSequence

// trimEnd with char array
fun CharSequence.trimEnd(vararg chars: Char): CharSequence

Parameters

This function accepts the following parameters −

  • Predicate: char->Boolean: A lambda function or predicate that takes a character as input and return true for char to be removed.
  • vararg chars: Char: A variable-length array of characters. Only trailing character in this array will be removed.

Return value

This function returns a string or char sequence with removed trailing characters.

Example 1: Use the Default trimEnd()

Following is the basic example, we use default trimEnd() function to remove the trailing white-space −

fun main() {
   val string = "  tutorialspoints India  "

   // use trimEnd()
   val newString = string.trimEnd()
   println("New string:${newString}")
}

Output

Following is the output −

New string:  tutorialspoints India

Example 2: Remove Trailing Number

Here, we remove the trailing number from string based on the predicate we pass in the trimEnd() function −

fun main() {
   val stringWithDigit = "123tutorialspoint456"
   // trimEnd with predicate
   println("New String: " + stringWithDigit.trimEnd { it.isDigit() })
}

Output

Following is the output −

New String: 123tutorialspoint

Example 3: Remove the Specific Trailing Character

The below example removes the specific trailing char from the character sequence by specifying "vararg" to the trimEnd() function −

fun main() {
   val stringWithSpecialChar = "**tutorials*point**"
   // trimEnd with special char
   println("new-string: " + stringWithSpecialChar.trimEnd('*'))
}

Output

Following is the output −

new-string: **tutorials*point
kotlin_strings.htm
Advertisements