Swift字符串分离

时间:2018-02-28 02:11:14

标签: arrays swift

我正在阅读包含格式数据的文件:

router.use('/foo', <MiddleWareFn> function(req,res,next){});

1990 3 6.4 1.0 9

所以生成的数组是 1991 1 5.3 12.0 10

当我只需要

["1990"][""][""][""]["3"]....

我想将此信息提取到数组或结构中。 但是当我试图:

["1991"]["3"]["6.4"]....

它创建了一个我不需要的空格数组。

数组应该只包含有用的值。

由于

2 个答案:

答案 0 :(得分:1)

如果.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)

答案 1 :(得分:1)

  1. 将多个连续空格转换为一个空格。

    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)
    
  2. 使用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)
    }
    
  3. 枚举单词。

    var words: [String] = []
    string.enumerateSubstrings(in: string.startIndex..<string.endIndex, options: .byWords) {word, _, _, _ in
        words.append(word!)
    }