This post will discuss how to remove leading and trailing whitespace from a string in Kotlin.

1. Using trim() function

The standard solution to trim a string is using the trim() function. Since the string is immutable in Kotlin, it returns a new string having leading and trailing whitespace removed. To just remove the leading whitespaces, use the trimStart() function. Similarly, use the trimEnd() function to remove the trailing whitespaces.

Download Code

 
Here’s an equivalent version using a predicate it <= ' ', which removes all the non-printable ASCII characters from the string (having ASCII code less or equal to the space).

Download Code

2. Using replace() function

The replace() function is overloaded to accept a regular expression and replace each substring of the char sequence that matches the given regular expression with the given replacement. It can be used as follows to trim a string:

Download Code

 
To remove either the leading whitespaces or the trailing whitespaces from the string, use the following utility functions:

3. Custom Routine

You can even write a custom routine for trimming a string, which doesn't involve using any regex and runs comparatively faster. Below is a simple custom implementation of the trim() function.

Download Code

 
The following utility function can be used to remove the leading or the trailing whitespaces from a string.

That's all about removing leading and trailing whitespace from a string in Kotlin.