Kotlin String - filter() Function



The Kotlin string filter() function is used to filter characters in a string based on a given predicate. It evaluates each character and includes it in the resulting string only if it satisfies the condition defined in the predicate.

Following are the use cases of this function −

  • Data Sanitization: It helps to remove the invalid or unwanted character from the input character sequence.
  • Text Analysis: It extract specific types of characters such as letters, digits, or symbols.
  • Custom Formatting: It filter out spaces, punctuation, or other unnecessary elements.
The filter() function does not modify the string; This creates a new filtered string. This function works with all classes implementing charSequence such as String, or StringBuilder.

Syntax

Following is the syntax of the Kotlin string filter() function −

fun CharSequence.filter(predicate: (Char) -> Boolean): String

Parameters

This function accepts a predicate that is a lambda function that defines the condition to filter character.

Return value

This function returns a string containing only the characters that satisfy the predicate.

Example 1: Filter Alphabetic String

This is the basic example of the filter() function, we filter the alphabetic character from the string −

fun main() {
   val input = "Tutorialspoint123!"
   // filter the alphabetic character
   val result = input.filter { it.isLetter() }
   println("Filtered string:" + result)
}

Output

Following is the output −

Filtered string:Tutorialspoint

Example 2: Count the Digit

In this example, we use the filter() to count the digits available in this string −

fun main() {
   val input = "51Tutorialspoint123!"
   // count the digit
   val total_digit = input.filter { it.isDigit() }.length
   println("Total Digit in this string:" + total_digit)
}

Output

Following is the output −

Total Digit in this string:5

Example 3: Filter the Punctuation Marks

In this example, we filter out the punctuation marks from the string using the filter() function −

fun main() {
   val input = "Hello, World! 123"
   // extracting the punctuation
   val symbols = input.filter { !it.isLetterOrDigit() && !it.isWhitespace() }
   println("punctuation: " + symbols)
}

Output

Following is the output −

punctuation: ,!

Example 4: Create a Custom Logic to Filter

Now here we create a custom logic, like filtering characters based on ASCII values −

fun main() {
   val input = "This is Tutorialspoint 500033"
   // A-Z and a-z ASCII range
   val filtered_string = input.filter { it.code in 65..90 || it.code in 97..122 }
   println("New string: " + filtered_string)
}

Output

Following is the output −

New string: ThisisTutorialspoint
kotlin_strings.htm
Advertisements