How to remove all non-numeric characters from a string in Kotlin

1 Answer

0 votes
/**
 * Removes all non-numeric characters from a string, returning a new string
 * containing only numeric digits (0-9).
 * 
 * @param input The source string containing alphanumeric and special characters.
 * @return A new String containing only digits.
 */
fun removeNonNumeric(input: String): String {
    // Filter the characters, retaining only digits using Kotlin's Char::isDigit
    return input.filter(Char::isDigit)
}

fun main() {
    // Test string provided
    val text = "123XYZ +9982-programming 10000000000001language"
    
    // Process the string
    val cleanedText = removeNonNumeric(text)

    // Output results
    println("Original: $text")
    println("Cleaned:  $cleanedText")
}


/*
run:

Original: 123XYZ +9982-programming 10000000000001language
Cleaned:  123998210000000000001

*/

 



answered 13 hours ago by avibootz

Related questions

...