gpt4 book ai didi

swift - 当字符串充满特殊字符时,如何在swift中提取双引号内的特定单词?

转载 作者:搜寻专家 更新时间:2023-11-01 06:40:08 25 4
gpt4 key购买 nike

从给定的数据即 -

session_id="8b55ed3af15dcf154aaaedd1bb667489"/ip_address="103.16.104.24"/last_activity="1460548532"

我如何提取 session_id、ip_address 和 last_activity 的值。我试过下面的代码,但它只适用于简单的字符串,当我分配给定的数据时,它显示错误

var testString: String = "session_id="8b55ed3af15dcf154aaaedd1bb667489"/ip_address="103.16.104.24"/last_activity="1460548532""

var data: String = testString
let extractedStringData = data.componentsSeparatedByString("/")

var session_id: String = extractedStringData[0]
var ip_address: String? = extractedStringData[1]
var last_activity: String? = extractedStringData [2]

任何建议都会有帮助
谢谢

最佳答案

可能有更实用的方法来做到这一点,但这个有效:

var testString: String = "session_id=\"8b55ed3af15dcf154aaaedd1bb667489\"/ip_address=\"103.16.104.24\"/last_activity=\"1460548532\""

let pairs: [String] = testString.characters.split("/").map(String.init)
var values = [String:String]()
pairs.forEach({
let pair: [String] = $0.characters.split("=").map(String.init)
values[pair[0]] = pair[1]
})

testString: String = "session_id=\"8b55ed3af15dcf154aaaedd1bb667489\"/ip_address=\"103.16.104.24\"/last_activity=\"1460548532\""
pairs: [String] = 3 values {
[0] = "session_id=\"8b55ed3af15dcf154aaaedd1bb667489\""
[1] = "ip_address=\"103.16.104.24\""
[2] = "last_activity=\"1460548532\""
}
values: [String : String] = 3 key/value pairs {
[0] = {
key = "last_activity"
value = "\"1460548532\""
}
[1] = {
key = "session_id"
value = "\"8b55ed3af15dcf154aaaedd1bb667489\""
}
[2] = {
key = "ip_address"
value = "\"103.16.104.24\""
}
}

关于swift - 当字符串充满特殊字符时,如何在swift中提取双引号内的特定单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36631295/

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