从objective-c中的NSString中删除非ASCII字符 [英] remove non ASCII characters from NSString in objective-c

查看:107
本文介绍了从objective-c中的NSString中删除非ASCII字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序可以同步用户填充的远程数据库中的数据。似乎人们从大量不同的操作系统和程序中复制和粘贴垃​​圾,这可能导致不同的隐藏非ASCII值导入系统。

I have an app that syncs data from a remote DB that users populate. Seems people copy and paste crap from a ton of different OS's and programs which can cause different hidden non ASCII values to be imported into the system.

例如我最终得到的这个:

For example I end up with this:

Artist:â â Ioco

这最终会在同步过程中被送回系统,我的JSON转换会加剧问题,各个地方的无效字符会导致我的应用程序崩溃。

This ends up getting sent back into system during sync and my JSON conversion furthers the problem and invalid characters in various places cause my app to crash.

如何搜索并清除这些无效字符?

How do I search for and clean out any of these invalid characters?

推荐答案

虽然我坚信支持unicode是正确的方法,这里是一个如何限制字符串只包含某些字符(在本例中为ASCII)的例子:

While I strongly believe that supporting unicode is the right way to go, here's an example of how you can limit a string to only contain certain characters (in this case ASCII):

NSString *test = @"Olé, señor!";

NSMutableString *asciiCharacters = [NSMutableString string];
for (NSInteger i = 32; i < 127; i++)  {
    [asciiCharacters appendFormat:@"%c", i];
}

NSCharacterSet *nonAsciiCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:asciiCharacters] invertedSet];

test = [[test componentsSeparatedByCharactersInSet:nonAsciiCharacterSet] componentsJoinedByString:@""];

NSLog(@"%@", test); // Prints @"Ol, seor!"

这篇关于从objective-c中的NSString中删除非ASCII字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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