Swift UTF8编码和非UTF8字符

我有一些来自json文件的文本。在本文中,我应用了UTF8编码,但是该编码器无法识别非标准字符,àèìòù并且为大写字符,是否有一种方法可以净化我的字符串?

我的功能:

func stringToUTF8String (stringaDaConvertire stringa: String) -> String {

let encodedData = stringa.dataUsingEncoding(NSUTF8StringEncoding)!

let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!

//println(attributedString.string)

return attributedString.string

}

回答:

我找到了解决方案。

UTF8采用8位表ASCII表,而UTF16采用16位ASCII表,解决方案很简单,只需将函数修改为:

func stringToUTF16String (stringaDaConvertire stringa: String) -> String {

let encodedData = stringa.dataUsingEncoding(NSUTF16StringEncoding)!

let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]

let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!

//println(attributedString.string)

return attributedString.string

}

以上是 Swift UTF8编码和非UTF8字符 的全部内容, 来源链接: utcz.com/qa/433212.html

回到顶部