2

I have a String which has many key value pairs appended by a & sign. i.e: params = key1=Hello&key2=Hello World&key3=Hi Hello

Is there a way to extract the values just by passing the keys present in the string? For example I want to extract the value of key1, key2, key3.

JMS
  • 271
  • 4
  • 15
  • If the *string* is part of an URL take a look at `URLComponents` and `URLQueryItem` – vadian Aug 17 '17 at 07:58
  • No, It is not a part of an URL. I am receiving an encoded string with just the parameters. After decoding it, I am getting the above string. – JMS Aug 17 '17 at 08:00
  • just use [yourString componentSeoratedByString:@"&"]; You will find an array. Now manipulate your array. – Gagan_iOS Aug 17 '17 at 08:08

3 Answers3

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

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


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

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

And in dictionary you will get your key-value pairs.

Joannes
  • 2,569
  • 3
  • 17
  • 39
Juri Noga
  • 4,363
  • 7
  • 38
  • 51
1

You can use URLComponents and URLQueryItem anyway by creating a dummy URL

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)
}

see also Best way to parse URL string to get values for keys?

vadian
  • 274,689
  • 30
  • 353
  • 361
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")]
Durdu
  • 4,649
  • 2
  • 27
  • 47
  • `index(of:)` is not sufficient because a value which is equal to a later occurring key would break the code. Just use `let keys = separated.enumerated().filter{$0.0 % 2 == 0}` instead, which would also run in O(n) instead of O(n^2). – Palle Aug 17 '17 at 09:05