remove non ASCII characters from NSString in objective-c

前端 未结 1 880
北海茫月
北海茫月 2020-12-06 19:56

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 hi

相关标签:
1条回答
  • 2020-12-06 19:58

    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!"
    
    0 讨论(0)
提交回复
热议问题