swift - 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\"
,因为我们知道它是一回事?
解决方案
好吧,这是一个 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\""]
推荐阅读
- sql - 预言机中的 TO_CHAR
- xpath - 如何在量角器中获取具有特定标签名称和文本的后代?
- r - 如何以循环形式重写这个R代码?(关于随机选择变量)
- android - 尝试将 youtube 视频添加到 ListItem
- android - SQL 查询到 Firebase 查询
- javascript - 将 Google 表格数据复制到最后一行下方的其他 Google 表格
- javascript - 如何读取两个不同的 xml 文件并在 javascript 中附加一个新的 xml 文件?
- equation - asciimath:方程数
- python - 如何编码时间strptime格式
- android - Android Kotlin 智能算子重载