首页 > 解决方案 > swift:使用字符串

问题描述

我们有一个简单的字符串:

let str = "\"abc\", \"def\",\"ghi\" , 123.4, 567, \"qwe,rty\""

如果我们这样做:

let parsedCSV = str
            .components(separatedBy: .newlines)
            .filter { !$0.isEmpty }
            .map { $0.components(separatedBy: ",") }
            .map { $0.map { $0.trimmingCharacters(in: .whitespaces) } }
print(parsedCSV)

我们得到这个:

[["\"abc\"", "\"def\"", "\"ghi\"", "123.4", "567", "\"qwe", "rty\""]]

是否有一个简单的解决方案(使用函数式编程)不拆分最后一个元素\"qwe,rty\",因为我们知道它是一回事?

标签: swiftstring

解决方案


好吧,这是一个 hack,它适用于这种情况....对于复杂问题不是很简单的解决方案...

let str = "\"abc\", \"def\",\"ghi\" , 123.4, 567, \"qwe,rty\""

let parsedCSV = str
    .components(separatedBy: .newlines)
    .filter { !$0.isEmpty }
    .map { $0.components(separatedBy: ",") }
    .map { $0.map { $0.trimmingCharacters(in: .whitespaces) } }.reduce([]) { (result, items) -> [String] in
        var goodItems = items.filter{ $0.components(separatedBy: "\"").count == 3 ||  $0.components(separatedBy: "\"").count == 1}
        let arr = items.filter{ $0.components(separatedBy: "\"").count == 2}
        var join:[String] = []
        for x in 0..<arr.count {
            let j = x + 1
            if j < arr.count {
                join = [arr[x] + "," + arr[j]]
            }
        }
        goodItems.append(contentsOf: join)
        return goodItems
}


print(parsedCSV)

打印出

["\"abc\"", "\"def\"", "\"ghi\"", "123.4", "567", "\"qwe,rty\""]


推荐阅读