Swift:从字符串

时间:2017-08-17 07:56:47

标签: ios swift3 alamofire

我有String,其中有许多键值对,附加了&符号。即:params = key1=Hello&key2=Hello World&key3=Hi Hello

有没有办法通过传递字符串中的键来提取值?例如,我想提取key1,key2,key3的值。

3 个答案:

答案 0 :(得分:1)

let string = "key1=Hello&key2=Hello World&key3=Hi Hello"

let components = s.components(separatedBy: "&")


var dictionary : [String : String] = [:]

for component in components{
  let pair = component.components(separatedBy: "=")
  dictionary[pair[0]] = pair[1]
}

dictionary中,您将获得键值对。

答案 1 :(得分:1)

无论如何,您可以通过创建虚拟网址

来使用URLComponentsURLQueryItem
let params = "key1=Hello&key2=Hello World&key3=Hi Hello"
if let components = URLComponents(string: "http://dummy.com/path?" + params.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!),
    let queryItems = components.queryItems {
    let arrayOfValues = queryItems.flatMap{ $0.value }
    print(arrayOfValues)
}

另见Best way to parse URL string to get values for keys?

答案 2 :(得分:0)

let params = "key1=Hello&key2=Hello World&key3=Hi Hello"

let sepparated = params.components(separatedBy: CharacterSet(charactersIn: "&="))
let keys = sepparated.enumerated().filter{$0.0 % 2 == 0}
print (keys) // [(offset: 0, element: "key1"), (offset: 2, element: "key2"), (offset: 4, element: "key3")]