— Kotlin, String Manipulation — 1 min read
Whitespace at the beginning or end of a string can sometimes cause issues when handling user input or processing data. In Kotlin, we can easily remove this whitespace using the trim
function. In this article, we will explore how to use Kotlin's trim
function effectively.
trim
functionThe trim
function is a built-in Kotlin function that removes leading and trailing whitespace from a string. It is often used to clean up user input or ensure consistency when working with strings in Android development.
Here's the syntax of the trim
function:
1fun String.trim(): String
The trim
function does not modify the original string; instead, it returns a new string with the leading and trailing whitespace removed.
Let's dive into some examples to see how the trim
function works.
1val text = " Hello, World! "2val trimmedText = text.trim()3
4println(trimmedText) // Output: "Hello, World!"
In this example, we have a string text
with leading and trailing whitespace. By calling trim()
on the string, we obtain a new string trimmedText
with the whitespace removed. Printing trimmedText
shows the expected output: "Hello, World!".
The trim
function also removes leading and trailing whitespace on each line of a multiline string.
1val multilineText = """2 Line 13 Line 24 Line 35""".trim()6
7println(multilineText)
Executing this code will output:
1Line 12Line 23Line 3
As you can see, the trim
function removes the whitespace at the beginning of each line, ensuring a clean and consistent formatting.
The trim
function can also be used to remove specific characters instead of just whitespace. You can pass in a character or a string of characters to the trim
function, and it will remove them from the start and end of the string.
1val text = "@@@Hello, World!@@@"2val trimmedText = text.trim('@')3
4println(trimmedText) // Output: "Hello, World!"
In this example, we have a string text
with leading and trailing "@" characters. By calling trim('@')
on the string, we get a new string trimmedText
with the "@" characters removed.
Kotlin's trim
function provides a convenient way to remove leading and trailing whitespace from strings in Android development. Whether it's cleaning up user input or processing data, the trim
function can help ensure the consistency and accuracy of your string operations. So go ahead, give Kotlin's trim
function a try and keep your strings clean and tidy!