我正在读取包含格式数据的文件:
1990 3 6.4 1.0 9
1991 1 5.3 12.0 10
所以得到的数组是["1990"][""][""][""]["3"]....
当我只需要
["1991"]["3"]["6.4"]....
我想将此信息提取到数组或结构中。但是当我试图:
let x = string.components(seperatedBy: .whitespaces)
它创建了一个我不需要的空格数组。
该数组应仅包含有用的值。
谢谢
let string = """
1990 3 6.4 1.0 9
1991 1 5.3 12.0 10
"""
let components = string.replacingOccurrences(of: "\\s+", with: " ", options: .regularExpression)
.components(separatedBy: .whitespaces)
Scanner
。
let scanner = Scanner(string: string)
var result: [String] = []
var value: NSString? = nil
while scanner.scanUpToCharacters(from: .whitespacesAndNewlines, into: &value) {
result.append(value as! String)
}
var words: [String] = []
string.enumerateSubstrings(in: string.startIndex..<string.endIndex, options: .byWords) {word, _, _, _ in
words.append(word!)
}
如果.whitespaces
不适合您,您可以尝试按空格字符拆分值。
let string = "1990 3 6.4 1.0 9 1991 1 5.3 12.0 10"
let strings = string.components(separatedBy: " ") // or .whitespaces to be more thorough
此外,您可以将值映射到实际数字。
let numbers = strings.flatMap(NumberFormatter().number)