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

1 Answer

0 votes
import Foundation

/// Removes all non-numeric characters from a string, returning a new string
/// containing only numeric digits (0-9).
///
/// - Parameter input: The source string containing alphanumeric and special characters.
/// - Returns: A new String containing only digits.
func removeNonNumeric(_ input: String) -> String {
    // Filter the characters, retaining only those within the standard ASCII digit range
    return String(input.filter { ("0"..."9").contains($0) })
}

// --- Example Usage ---
let text = "123XYZ +9982-programming 10000000000001language"

// Process the string
let cleanedText = removeNonNumeric(text)

// Output results
print("Original: \(text)")
print("Cleaned:  \(cleanedText)")


/*
run:

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

*/

 



answered 13 hours ago by avibootz

Related questions

...