Kotlin – Filter Characters of String

To filter characters in a String in Kotlin, use String.filter() method.

Given a string str1, and if we would like to filter the characters of this string using a predicate (some condition) predicate, call filter() method on string str1 and pass the predicate predicate as argument to the method as shown below.

str1.filter(predicate: (Char) -> Boolean)

filter() method returns a filtered String value based on the predicate.

Example 1 – Filter only Digits From String

In this example, we will take a string in str1, and filter only digits using String.filter() method.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcd 125 e77fg ABCD"
    val result = str1.filter({ it -> it.isDigit() })
    println("Filtered String  : " + result)
}

Output

Filtered String  : 12577

Example 2 – Filter only Letters From String

In this example, we will take a string in str1, and filter only letters using String.filter() method.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcd 125 e77fg ABCD"
    val result = str1.filter({ it -> it.isLetter() })
    println("Filtered String  : " + result)
}

Output

Filtered String  : abcdefgABCD

Example 3 – Filter only Uppercase Letters From String

In this example, we will take a string in str1, and filter only uppercase letters using String.filter() method.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcd 125 e77fg ABCD"
    val result = str1.filter({ it -> it.isUpperCase() })
    println("Filtered String  : " + result)
}

Output

Filtered String  : ABCD

Conclusion

In this Kotlin Tutorial, we learned how to filter the characters of give String, using String.filter() method, with the help of Kotlin example programs.