Swift UTF8编码和非UTF8字符 [英] Swift UTF8 encoding and non UTF8 character

查看:554
本文介绍了Swift UTF8编码和非UTF8字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've a some text from json file. In this text I've applied UTF8 encode but this encoder don't recognize a non standard character àèìòù and it's capital char, is there a method to purify my string?

我的功能:

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表,通过将函数修改为以下方法,解决方案很简单:

The UTF8 take 8 bit of table ASCII, and the UTF16 take 16 bit ASCII table, the solution is simple by modifying my function to:

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字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆