How to extract all digits from a string in Kotlin

1 Answer

0 votes
/*
    A small program that demonstrates how to extract all digits
    from a string using Kotlin's expressive standard library.

    The approach:
      - Use a dedicated function for clarity
      - Iterate through characters using Kotlin's built‑in tools
      - Filter only digit characters
      - Build the result efficiently
*/

fun extractDigits(s: String): String {
    /*
        Walk through each character and keep only those
        recognized as digits. Kotlin's Char.isDigit()
        is Unicode‑aware and efficient.
    */
    return s.filter { it.isDigit() }
}

fun main() {
    // Example input string
    val str = "5 rustc#8go 9001 c c++ 17python"

    // Extract digits
    val digits = extractDigits(str)

    // Display results
    println("Original: $str")
    println("Digits:   $digits")
}


/*
run:

Original: 5 rustc#8go 9001 c c++ 17python
Digits:   58900117

*/

 



answered Sep 17 by avibootz
...