Remove characters in NSCharacterSet from NSString

浪尽此生 提交于 2019-12-03 23:33:38

问题


I have an NSCharacterSet which contains all the characters I want to remove from my NSString.

How can I do that?


回答1:


If you're not too worried about efficiency, a simple way would be [[myString componentsSeparatedByCharactersInSet:myCharacterSet] componentsJoinedByString:@""].

Otherwise, you could run through the characters in a loop, appending ones that weren't in the set onto a new string. If you do it that way, remember to use an NSMutableString for your result as you're building it up.




回答2:


Checkout the following code:

@implementation NSString(Replacing)

- (NSString *)stringByReplacingCharactersInSet:(NSCharacterSet *)charSet withString:(NSString *)aString {
    NSMutableString *s = [NSMutableString stringWithCapacity:self.length];
    for (NSUInteger i = 0; i < self.length; ++i) {
        unichar c = [self characterAtIndex:i];
        if (![charSet characterIsMember:c]) {
            [s appendFormat:@"%C", c];
        } else {
            [s appendString:aString];
        }
    }
    return s;
}


@end

If you specify a replacement string of @"" you would remove the characters in the set.




回答3:


You can use an NSScanner to scan through the string, scanning a chunk of characters-not-in-the-set, appending it to your result string, scanning the characters-in-the-set into a variable you otherwise ignore, and repeating until the scanner reaches the end.



来源:https://stackoverflow.com/questions/3476611/remove-characters-in-nscharacterset-from-nsstring

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