Remove leading and trailing whitespace from a string in Kotlin
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.
|
1 2 3 4 |
fun main() { val s = " [Some Text] " println(s.trim()) // [Some Text] } |
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).
|
1 2 3 4 |
fun main() { val s = " [Some Text] " println(s.trim { it <= ' ' }) // [Some Text] } |
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:
|
1 2 3 4 5 6 7 8 |
fun trim(s: String): String { return s.replace("^\\s+|\\s+$".toRegex(), "") } fun main() { val s = " [Some Text] " println(trim(s)) // [Some Text] } |
To remove either the leading whitespaces or the trailing whitespaces from the string, use the following utility functions:
|
1 2 3 4 5 6 7 |
fun ltrim(str: String): String { return str.replace("^\\s+".toRegex(), "") } fun rtrim(str: String): String { return str.replace("\\s+$".toRegex(), "") } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun trim(s: String): String { var i = 0 while (i < s.length && s[i].isWhitespace()) { i++ } var j = s.length - 1 while (j >= 0 && s[j].isWhitespace()) { j-- } return s.substring(i, j + 1) } fun main() { val s = " [Some Text] " println(trim(s)) // [Some Text] } |
The following utility function can be used to remove the leading or the trailing whitespaces from a string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun ltrim(str: String): String { var i = 0 while (i < str.length && str[i].isWhitespace()) { i++ } return str.substring(i) } fun rtrim(str: String): String { var i = str.length - 1 while (i >= 0 && str[i].isWhitespace()) { i-- } return str.substring(0, i + 1) } |
That's all about removing leading and trailing whitespace from a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)