替换特殊字符的问题

时间:2012-11-21 06:58:12

标签: iphone xcode ios5

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

- (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;
}

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:3)

试试这个......

NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", resultString);

答案 2 :(得分:0)

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