本文介绍了Swift如何从字符串中获取整数并将其转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要从字符串中提取数字并将它们放入Swift中的新数组中。
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"
我试图循环每个角色,我不知道比较字符和Int。
I tried to loop each characters and I have no idea to compare between Characters and Int.
推荐答案
首先,我们拆分字符串,以便我们处理单个项目。然后我们使用 NSCharacterSet
来仅选择数字。
First, we split the string so we can process the single items. Then we use NSCharacterSet
to select the numbers only.
import Foundation
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let strArr = str.split(separator: " ")
for item in strArr {
let components =
item.components(separatedBy: CharacterSet.decimalDigits.inverted)
let part: String = components.joined()
if let intVal = Int(part) {
print("this is a number -> \(intVal)")
}
}
Swift 4 :
let string = "I have to buy 3 apples, 7 bananas, 10eggs"
let stringArray = string.components(separatedBy: CharacterSet.decimalDigits.inverted)
for item in stringArray {
if let number = Int(item) {
print("number: \(number)")
}
}
这篇关于Swift如何从字符串中获取整数并将其转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!