How to convert string to unicode(UTF-8) string in Swift?

后端 未结 3 1974
终归单人心
终归单人心 2020-12-10 11:48

How to convert string to unicode(UTF-8) string in Swift?

In Objective I could write smth like that:

NSString *str = [[NSString alloc] initWithUTF8Str         


        
相关标签:
3条回答
  • 2020-12-10 12:19

    Swift 4:

    let str = String(describing: strToDecode.cString(using: String.Encoding.utf8))
    
    0 讨论(0)
  • 2020-12-10 12:21

    Use this code,

    let str = String(UTF8String: strToDecode.cStringUsingEncoding(NSUTF8StringEncoding))
    

    hope its helpful

    0 讨论(0)
  • 2020-12-10 12:41

    Swift 4 I have created a String extension

    func utf8DecodedString()-> String {
         let data = self.data(using: .utf8)
         if let message = String(data: data!, encoding: .nonLossyASCII){
                return message
          }
          return ""
    }
    
    func utf8EncodedString()-> String {
         let messageData = self.data(using: .nonLossyASCII)
         let text = String(data: messageData!, encoding: .utf8)
         return text
    }
    
    0 讨论(0)
提交回复
热议问题