如何在Swift中将字符串转换为unicode(UTF-8)字符串?

时间:2023-01-05 16:25:47

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

如何在Swift中将字符串转换为unicode(UTF-8)字符串?

In Objective I could write smth like that:

在Objective中,我可以这样写smth

NSString *str = [[NSString alloc] initWithUTF8String:[strToDecode cStringUsingEncoding:NSUTF8StringEncoding]];

how to do smth similar in Swift?

如何在Swift中做类似的smth ?

4 个解决方案

#1


5  

Use this code,

使用这个代码,

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

hope its helpful

希望它有用

#2


4  

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
}

#3


2  

Swift 4:

let str = String(describing: strToDecode.cString(using: String.Encoding.utf8)

#4


1  

Swift

斯威夫特

let esc_str = str.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)

#1


5  

Use this code,

使用这个代码,

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

hope its helpful

希望它有用

#2


4  

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
}

#3


2  

Swift 4:

let str = String(describing: strToDecode.cString(using: String.Encoding.utf8)

#4


1  

Swift

斯威夫特

let esc_str = str.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)