Kotlin String - trim() Function



The Kotlin string trim() function returns a new string or subsequence by removing leading and trailing characters from the original char sequence or sequence based on the specified condition.

It can remove whitespace, characters matching a predicate, or specific characters provided in an char array.

The word "trims" means to remove or cut something from a string to make it orderly. This function removes special characters or white-space from the leading and trailing, but not the middle, character sequences.

Syntax

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

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

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

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

Parameters

This function accpets the following parameters −

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

Return value

This function returns a string or char sequence.

Example 1: Use Default Trim()

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

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

   // use trim()
   val newString = string.trim()
   println("New string:" + newString)
}

Output

Following is the output −

New string:tutorialspoints India

Example 2: Remove the Digits

Here, we remove the numeric character from the string based on the predicate we pass in the trim() function −

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

Output

Following is the output −

stringWithoutDigit: tutorialspoint

Example 3: Trimming with Special Character

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

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

Output

Following is the output −

stringWithoutSpeciaCharacter: tutorials*point
kotlin_strings.htm
Advertisements