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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37087325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:00:56  来源:igfitidea点击:

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

iosswiftunicodeutf-8utf-16

提问by Dirder

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

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

In Objective I could write smth like that:

在目标中,我可以这样写:

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

how to do smth similar in Swift?

如何在 Swift 中做类似的事情?

采纳答案by Iyyappan Ravi

Use this code,

使用此代码,

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

hope its helpful

希望它有帮助

回答by Alessandro Ornano

Swift 4:

斯威夫特 4:

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

回答by Gurjinder Singh

Swift 4 I have created a String extension

Swift 4 我创建了一个字符串扩展

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
}