-1

I have this String -

&to[]=0532332028&to[]=0532332027

I want to convert this String to (UTF8) -

%26to%5B%5D%3D0532332028%26to%5B%5D%3D0532332027

I already try this Code -

let str = String(UTF8String: "&to[]=0532332028&to[]=0532332027".cStringUsingEncoding(NSUTF8StringEncoding)!)

Thanks

Sailendra
  • 1,318
  • 14
  • 29

2 Answers2

2

Try to use this code:

let text = "&to[]=0532332028&to[]=0532332027"
let output = text.addingPercentEncoding(withAllowedCharacters: .alphanumerics)

The output:

"%26to%5B%5D%3D0532332028%26to%5B%5D%3D0532332027"
Quoc Le
  • 416
  • 3
  • 9
1

To convert the string to UTF8, you can follow the code

    let text = "&to[]=0532332028&to[]=0532332027"
    let encodeText = text.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    print("encodeText : \(encodeText)")

Output : encodeText : &to%5B%5D=0532332028&to%5B%5D=0532332027

But by the above code, you won't get %26 for "&", If you want it You can create a custom method to replace "&" with "%26" by using "stringByReplacingOccurrencesOfString" method.

Hope it helps.

Janmenjaya
  • 4,149
  • 1
  • 23
  • 43
  • Thanks. Another Solution - let strNew = CFURLCreateStringByAddingPercentEscapes( nil, "&to[]=0532332028&to[]=0532332027", nil, "!*'();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue ) print("encodeText : \(strNew)") – kush Thakkar Oct 20 '16 at 12:03
  • @kushThakkar, Hmm.. but the method is deprecated in iOS 9. – Janmenjaya Oct 20 '16 at 12:09