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 ([cc lang=”objc” inline=”true” width=”0″ theme=”geshi”]NSCharacterSet *illegalCharacterSet[/cc] or [cc lang=”objc” inline=”true” width=”0″ theme=”geshi”]NSCharacterSet *symbolCharacterSet[/cc], say) to be easily and efficiently removed. This fills a gap in between the [cc lang=”objc” inline=”true” width=”0″ theme=”geshi”]stringByTrimmingCharactersInSet:[/cc] and [cc lang=”objc” inline=”true” width=”0″ theme=”geshi”]stringByReplacingCharactersInRange: withString:[/cc] & [cc lang=”objc” inline=”true” width=”0″ theme=”geshi”]stringByReplacingOccurrencesOfString: withString:[/cc] methods, which only act upon the ends of the receiver or require a continuous range or fixed string respectively.

[cc lang=”objc” width=”0″ line_numbers=”true” theme=”geshi”]
//
// 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
[/cc]