gpt4 book ai didi

iphone - 从 Objective-c 中的 NSString 中删除非 ASCII 字符

转载 作者:太空狗 更新时间:2023-10-30 03:46:41 24 4
gpt4 key购买 nike

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

例如我最终得到这个:

Artist:â â Ioco

这最终会在同步期间被发送回系统,我的 JSON 转换进一步加剧了问题,并且各个地方的无效字符导致我的应用程序崩溃。

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

最佳答案

虽然我坚信支持 unicode 是正确的做法,但这里有一个示例,说明如何将字符串限制为仅包含某些字符(在本例中为 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!"

关于iphone - 从 Objective-c 中的 NSString 中删除非 ASCII 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6361586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com