我需要在Swift中从字符串中提取数字并将它们放入一个新数组中。
var str = "I have to buy 3 apples, 7 bananas, 10eggs"
我试图循环每个字符,但不知道如何比较字符和整数。
Swift 3/4
let string = "0kaksd020dk2kfj2123"
if let number = Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) {
// Do something with this number
}
你也可以创建一个类似的扩展:
extension Int {
static func parse(from string: String) -> Int? {
Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
}
}
然后稍后像这样使用它:
if let number = Int.parse(from: "0kaksd020dk2kfj2123") {
// Do something with this number
}
首先,我们将字符串拆分,以便处理单个项。然后,我们使用NSCharacterSet
仅选择数字。
import Foundation
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let strArr = str.split(separator: " ")
for item in strArr {
let part = item.components(separatedBy: CharacterSet.decimalDigits.inverted).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)")
}
}
extractNumbers
的方法。 - Vincent Saluzzofunc matchesForRegexInText(regex: String!, text: String!) -> [String] {
let regex = NSRegularExpression(pattern: regex,
options: nil, error: nil)!
let nsString = text as NSString
let results = regex.matchesInString(text,
options: nil, range: NSMakeRange(0, nsString.length))
as! [NSTextCheckingResult]
return map(results) { nsString.substringWithRange($0.range)}
}
你可以轻松地通过使用
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let numbersAsStrings = matchesForRegexInText("\\d+", str) // [String]
let numbersAsInts = numbersAsStrings.map { $0.toInt()! } // [Int]
println(numbersAsInts) // [3, 7, 10]
模式"\d+"
匹配一个或多个十进制数字。
当然,如果出于某种原因您更喜欢不使用帮助函数来完成同样的操作,则也可以这样做:
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let regex = NSRegularExpression(pattern: "\\d+", options: nil, error: nil)!
let nsString = str as NSString
let results = regex.matchesInString(str, options: nil, range: NSMakeRange(0, nsString.length))
as! [NSTextCheckingResult]
let numbers = map(results) { nsString.substringWithRange($0.range).toInt()! }
println(numbers) // [3, 7, 10]
不使用正则表达式的替代方案:
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let digits = "0123456789"
let numbers = split(str, allowEmptySlices: false) { !contains(digits, $0) }
.map { $0.toInt()! }
println(numbers) // [3, 7, 10]
let str = "Hello 1, World 62"
let intString = str.componentsSeparatedByCharactersInSet(
NSCharacterSet
.decimalDigitCharacterSet()
.invertedSet)
.joinWithSeparator("")
那将会得到一个包含所有数字的字符串,然后你可以这样做:
let int = Int(intString)
只要确保将其解包,因为let int = Int(intString)
是可选项。
对我来说,将其作为字符串扩展更有意义,可能只是品味的问题:
extension String {
func parseToInt() -> Int? {
return Int(self.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
}
}
if let number = "0kaksd020dk2kfj2123".parseToInt() {
// Do something with this number
}
参照@flashadvanced的答案,我发现以下内容对我来说更加简短和简单。
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let component = str.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let list = component.filter({ $0 != "" }) // filter out all the empty strings in the component
print(list)
已经在测试环境中尝试过,并且实现了预期的效果
希望这对你有所帮助 :)
Swift 5:
extension String {
var allNumbers: [Int] {
let numbersInString = self.components(separatedBy: .decimalDigits.inverted).filter { !$0.isEmpty }
return numbersInString.compactMap { Int($0) }
}
}
你可以获取所有数字,例如:
var str = "I have to buy 3 apples, 7 bananas, 10eggs"
// numbers = [3, 7, 10]
numbers = str.allNumbers
Swift 2.2
let strArr = str.characters.split{$0 == " "}.map(String.init)
for item in strArr {
let components = item.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let part = components.joinWithSeparator("")
if let intVal = Int(part) {
print("this is a number -> \(intVal)")
}
}
// This will only work with single digit numbers. Works with “10eggs” (no space between number and word
var str = "I have to buy 3 apples, 7 bananas, 10eggs"
var ints: [Int] = []
for char:Character in str {
if let int = "\(char)".toInt(){
ints.append(int)
}
}
// This will work with multi digit numbers. Does NOT work with “10 eggs” (has to have a space between number and word)
var str = "I have to buy 3 apples, 7 bananas, 10 eggs"
var ints: [Int] = []
var strArray = split(str) {$0 == " "}
for subString in strArray{
if let int = subString.toInt(){
ints.append(int)
}
}
感谢所有回答我的问题的人。
我正在学习Swift语法,因此我正在寻找一个仅使用Swift语法的代码块。
我得到了一个答案。也许这不是解决问题的最简单方法,但它仅使用了Swift语言。
var article = "I have to buy 3 apples, 7 bananas, 10 eggs"
var charArray = Array(article)
var unitValue = 0
var total = 0
for char in charArray.reverse() {
if let number = "\(char)".toInt() {
if unitValue==0 {
unitValue = 1
}
else {
unitValue *= 10
}
total += number*unitValue
}
else {
unitValue = 0
}
}
println("I bought \(total) apples.")