我正在尝试将此字符串拆分为数组,稍后将其转换为字典
let string = "test=1&name=Noodle&item=100"
let edit = string.components(separatedBy: "=")
// string.components(separatedBy: "=" && "&")???
但这只会将字符串用一个字符分开,即“ =“
我想要实现的是用两个字符“ =”和“&”分隔字符串。我该如何实现?
答案 0 :(得分:2)
您可以这样做:
func stringConvert(string: String) -> [String: Any] {
let keysAndValues = string.components(separatedBy: "&")
let arraysOfPairs = keysAndValues.map { $0.components(separatedBy: "=") }
let tuples = arraysOfPairs.map { ($0[0], $0[1]) }
let d = Dictionary(uniqueKeysWithValues: tuples)
return d
}
let str = "test=1&name=Noodle&item=100"
let dict = stringConvert(string: str)
//["test": "1", "item": "100", "name": "Noodle"]
答案 1 :(得分:2)
您所能做的就是替换字符串中出现的字符,然后将其分开
let string = "test=1&name=Noodle&item=100"
let edit = string.replacingOccurrences(of: "&", with: "=").components(separatedBy: "=")