Issue with replacing special characters

本秂侑毒 提交于 2020-01-02 12:27:25

问题


Im having a issue with removing special characters from the string .I used the following code.But dint work.Please suggest me better logic

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

回答1:


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



回答2:


Try this...

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



回答3:


Try starting from the end of the string and work backwards instead of going from front to back, since you're likely to accidentally (and unintentionally) skip characters when the previous character gets deleted.



来源:https://stackoverflow.com/questions/13487931/issue-with-replacing-special-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!