How to extract all digits from a string in Swift

1 Answer

0 votes
import Foundation

/*
    extractDigits
    -------------
    Walks through the input string and collects only characters
    that are recognized as digits.

    Swift's Character.isNumber provides Unicode‑aware digit detection.
    The function uses a simple and efficient filter operation
    followed by String construction.
*/
func extractDigits(_ s: String) -> String {
    // Filter characters that are digits and build a new string
    let digits = s.filter { $0.isNumber }
    return String(digits)
}

//
// Main execution
//
let str = "5 rustc#8go 9001 c c++ 17python"

// Extract digits
let digits = extractDigits(str)

// Display results
print("Original: \(str)")
print("Digits:   \(digits)")


/*
run:

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

*/

 



answered Sep 17 by avibootz
...