To trim a string in Kotlin, you can use the trim()
, trimStart()
, and trimEnd()
methods of the String class.
In this example,
str1
with a value of " Hello World "
.trim()
method on str1
to remove leading and trailing whitespace characters.fun main(args: Array<String>) {
val str1 = " Hello World ";
val trimmedStr1 = str1.trim()
print("Trimmed string is: '$trimmedStr1'");
}
Trimmed string is: 'Hello World'
In this example,
str2
with a value of " apple"
.trimStart()
method on str2
to remove leading whitespace characters.fun main(args: Array<String>) {
val str2 = " apple";
val trimmedStr2 = str2.trimStart()
print("Trimmed string is: '$trimmedStr2'");
}
Trimmed string is: 'apple'
In this example,
str3
with a value of "banana "
.trimEnd()
method on str3
to remove trailing whitespace characters.fun main(args: Array<String>) {
val str3 = "banana ";
val trimmedStr3 = str3.trimEnd()
print("Trimmed string is: '$trimmedStr3'");
}
Trimmed string is: 'banana'
In this tutorial, we learned How to Trim a String in Kotlin language with well detailed examples.