More fun with NSStrings in Objective C

Sometimes, it’s the simple things which can be the most handy. Here’s a quick category on NSString to allow all characters within a set (NSCharacterSet *illegalCharacterSet or NSCharacterSet *symbolCharacterSet, say) to be easily and efficiently removed. This fills a gap in between the stringByTrimmingCharactersInSet: and stringByReplacingCharactersInRange: withString: & stringByReplacingOccurrencesOfString: withString: methods, which only act upon the ends of the receiver or require a continuous range or fixed string respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//
//  NSString+stringByRemovingCharactersInSet
//  Æther Tool
//
//  Created by Stuart Shelton on 29/01/2010.
//  Copyright 2010 - 2011, Stuart Shelton.  All rights reserved.
//

@interface NSString (StringByRemovingCharactersInSet)

- (NSString *)stringByRemovingCharactersInSet: (NSCharacterSet *)characterSet;

@end

@implementation NSString (StringByRemovingCharactersInSet)

- (NSString *)stringByRemovingCharactersInSet: (NSCharacterSet *)characterSet {
    NSString *result = @"";

    for( NSString *component in [self componentsSeparatedByCharactersInSet: characterSet] )
        result = [result stringByAppendingString: component];

    return result;
}

@end