In this tutorial, you shall learn how to filter character in a given string in Kotlin, using String.filter() function, with examples.

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.

</>
Copy
str1.filter(predicate: (Char) -> Boolean)

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

Examples

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

</>
Copy
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

2. Filter only letters in string

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

Kotlin Program

</>
Copy
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

3. Filter only Uppercase letters in string

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

Kotlin Program

</>
Copy
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.