Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift How to get integer from string and convert it into integer

I need to extract numbers from string and put them into a new array in Swift.

var str = "I have to buy 3 apples, 7 bananas, 10eggs" 

I tried to loop each characters and I have no idea to compare between Characters and Int.

like image 220
alphonse Avatar asked May 20 '15 07:05

alphonse


People also ask

Can you convert strings to ints?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.

How do I cast an int in Swift?

swift1min read To convert a float value to an Int, we can use the Int() constructor by passing a float value to it. Note: When we use this conversion the Integer is always rounded to the nearest downward value, like 12.752 to 12 or 6.99 to 6 .

How do you convert data to int?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .


1 Answers

Swift 3/4

let string = "0kaksd020dk2kfj2123" if let number = Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) {     // Do something with this number } 

You can also make an extension like:

extension Int {     static func parse(from string: String) -> Int? {         return Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())     } } 

And then later use it like:

if let number = Int.parse(from: "0kaksd020dk2kfj2123") {      // Do something with this number }  
like image 200
George Maisuradze Avatar answered Sep 20 '22 19:09

George Maisuradze