Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter characters from a string in Swift 4

Tags:

string

swift

In the following Swift 3 code I'm extracting all numbers from a string but I can not figure out how to do the same thing in Swift 4.

var myString = "ABC26FS464"

let myNumbers = String(myString.characters.filter { "01234567890".characters.contains($0)})

print(myNumbers) // outputs 26464

How can I extract all numbers from a string in Swift 4?

like image 222
fs_tigre Avatar asked Nov 10 '17 23:11

fs_tigre


People also ask

How do I filter a string in Swift?

To filter strings in a Swift String Array based on length, call filter() method on this String Array, and pass the condition prepared with the string length as argument to the filter() method. filter() method returns an array with only those elements that satisfy the given predicate/condition.

How do I remove a specific character from a string in Swift?

In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from the string. It will return a character that was removed from the given string.

How do you remove all occurrences of a character from a string in Swift?

In this tutorial, we will learn about the Swift String removeAll() method with the help of examples. The removeAll() method removes all the elements from the string based on a given condition.

How do I remove the first character from a string in Swift 5?

The dropFirst() method removes the first character of the string.


2 Answers

Easiest:

As "Character" has almost all the most used character checking with ".isXY" computed properties, you can use this pattern, which seems to be the most convenient and Swifty way to do string filtering.

/// Line by line explanation.
let str = "Stri1ng wi2th 3numb4ers".filter(\.isNumber) // "1234"
let int = Int(str)                                     // Optional<Int>(1234)
let unwrappedInt = int!                                // 1234

/// Solution.
extension String {

    /// Numbers in the string as Int.
    /// 
    /// If doesn't have any numbers, then 0.
    var numbers: Int {
        Int(filter(\.isNumber)) ?? 0
    }

    /// Numbers in the string as Int.
    ///
    /// If doesn't have any numbers, then nil.
    var optionalNumbers: Int? {
        Int(filter(\.isNumber))
    }
}
like image 107
Ádám Nagy Avatar answered Oct 22 '22 00:10

Ádám Nagy


Swift 4 makes it a little simpler. Just remove the .characters and use

let myNumbers = myString.filter { "0123456789".contains($0) }

But to really do it properly, you might use the decimalDigits character set...

let digitSet = CharacterSet.decimalDigits
let myNumbers = String(myString.unicodeScalars.filter { digitSet.contains($0) })
like image 41
85Camaro Avatar answered Oct 22 '22 01:10

85Camaro