gpt4 book ai didi

ios - 拆分 Swift 字符串复杂

转载 作者:行者123 更新时间:2023-11-28 10:07:09 25 4
gpt4 key购买 nike

我想拆分一个纯字符串形式的响应。响应如下

Result Set, Status: N/A Host: somesite.com is Connection live: true Status Connection: deny heart beat: dead

需要根据此响应创建字典,例如 ResultSetDic[String:String]

Status: N/A  
Host: somesite.com
is Connection live: true
Status Connection: deny
heart beat: dead

尝试使用 NSRegularExpression、Range、Split 等各种方式拆分响应字符串,但没有一种更清晰,并且使用多个字符串结果集来逐个解析,这并不整洁。

在字典中拆分响应的任何有用方法。在上面的响应中,键总是固定的。

最佳答案

使这个可解析的是,每个 value 只是一个 wordkeyvalue: 分隔。

首先我确定下一个键的结尾,然后添加下一个单词作为它的值。

func testing() {
let input = "Result Set, Status: N/A Host: somesite.com is Connection live: true Status Connection: deny heart beat: dead"

var step1 = input.split(separator: " ")
guard let index = step1.firstIndex(where: { $0.contains(",") }) else {
fatalError("Does not contain `,`. at the beginning.")
}
step1.removeFirst(index + 1)

var step2 = step1
var output = [String: String]()
repeat {
guard let index = step2.firstIndex(where: { $0.contains(":") }) else {
// If the last part has no :, can add it under `end`.
// output["end"] = step2.joined(separator: " ")
step2.removeAll()
break
}
let key = step2[0...index].joined(separator: " ").trimmingCharacters(in: CharacterSet(charactersIn: ":"))
let value = step2[index + 1]
output [key] = String(value)
step2.removeFirst(index + 2)

} while step2.count != 0

output.forEach{
print("\($0.key): \($0.value)")
}
}


// Output:
// Host: somesite.com
// Status Connection: deny
// Status: N/A
// heart beat: dead
// is Connection live: true

编辑:Array.firstIndex(where:) 似乎是 Xcode10+,所以在 Xcode9.4 中你可以尝试:

extension Array {
func firstIndex(where predicate: (Element) throws -> Bool) rethrows -> Int? {
for index in indices where try predicate(self[index]) { return index }
return nil
}
}

Edit2:从 Leo 添加 .firstIndex(where:) 的向后兼容方式:

extension Collection {
func firstIndex(where predicate: (Element) throws -> Bool) rethrows -> Index? {
return try index(where: predicate)
}
}

关于ios - 拆分 Swift 字符串复杂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52008779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com