一尘不染

Swift UTF8编码和非UTF8字符

swift

我有一些来自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
}

阅读 1134

收藏
2020-07-07

共1个答案

一尘不染

我找到了解决方案。

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
}
2020-07-07