Skip to content
DeveloperMemos

Using Kotlin's trim function

Kotlin, String Manipulation1 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.

The trim function

The 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.

Example 1: Basic usage

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!".

Example 2: Trimming multiple lines

The trim function also removes leading and trailing whitespace on each line of a multiline string.

1val multilineText = """
2 Line 1
3 Line 2
4 Line 3
5""".trim()
6
7println(multilineText)

Executing this code will output:

1Line 1
2Line 2
3Line 3

As you can see, the trim function removes the whitespace at the beginning of each line, ensuring a clean and consistent formatting.

Example 3: Trim specific characters

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.

Wrapping Up

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!