Kotlin String - trimStart() Function



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

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

Syntax

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

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

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

// trimStart with char array
fun CharSequence.trimStart(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 leading character in this array will be removed.

Return value

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

Example 1: Use Default TrimStart()

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

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

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

Output

Following is the output −

New string: tutorialspoints India

Example 2: Use Predicate to Remove Leading Number

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

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

Output

Following is the output −

New String: tutorialspoint456

Example 3: Remove the Specific Leading Character

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

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

Output

Following is the output −

stringWithoutSpeciaCharacter: tutorials*point**
kotlin_strings.htm
Advertisements