Trim a Substring in Kotlin
To trim whitespaces from the edges of a string in Kotlin, you can use String.trim()
function.
Call trim()
function on the given String object str
.
str.trim()
trim()
function returns a new string by removing all the whitespaces characters from the starting and ending of the string. The whitespace characters in between the non-space character are left as is.
Examples
Trim string " Hello World "
Consider a scenario where we get a string with some spaces at the edges of the string, and we would like to remove these spaces.
Kotlin Program
fun main() {
val str = " Hello World "
val resultString = str.trim()
println(resultString)
}
Output
Hello World