2

我在从字符串中删除特殊字符时遇到问题。我使用了以下代码。但是 dint 工作。请建议我更好的逻辑

- (NSString *)trimmedReciString:(NSString *)stringName 
{
    NSCharacterSet *myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"-/:;()$&@\".,?!\'[]{}#%^*+=_|~<>€£¥•."];
    for (int i = 0; i < [stringName length]; i++) {
        unichar c = [stringName characterAtIndex:i];
        if ([myCharSet characterIsMember:c]) {
            NSLog(@"%@",[NSString stringWithFormat:@"%c",[stringName characterAtIndex:i]]);
            stringName =  [stringName stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%c",[stringName characterAtIndex:i]] withString:@""];  

        }
    }
    return stringName;
}
4

3 回答 3

8
NSString *s = @"$$$hgh$g%k&fg$$tw/-tg";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"-/:;()$&@\".,?!\'[]{}#%^*+=_|~<>€£¥•."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"String is: %@", s);
于 2012-11-21T07:38:21.973 回答
3

试试这个...

NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", resultString);
于 2012-11-21T07:09:48.253 回答
0

尝试从字符串的末尾开始并向后工作,而不是从前到后,因为当前一个字符被删除时,您可能会意外(并且无意地)跳过字符。

于 2012-11-21T07:05:29.913 回答