views:

59

answers:

1

I want to replace several different groups of characters in one NSString. Currently I am doing it with several repeating methods, however I am hoping there is a way of doing this in one method:

NSString *result = [html stringByReplacingOccurrencesOfString:@"<B&" withString:@" "];
NSString *result2 = [result stringByReplacingOccurrencesOfString:@"</B>" withString:@" "];

NSString *result3 = [result2 stringByReplacingOccurrencesOfString:@"gt;" withString:@" "];
return [result3 stringByReplacingOccurrencesOfString:@" Description  " withString:@""];
A: 

I don't think there is anything in the SDK, but you could at least use a category for this so you can write something like this:

NSDictionary *replacements = [NSDictionary dictionaryWithObjectsAndKeys:
                                @" ", @"<B&",
                                @" ", @"</B>",
                                @" ", @"gt;"
                                @"" , @" Description  ",
                              nil];
return [html stringByReplacingStringsFromDictionary:replacements];

... by using something like the following:

@interface NSString (ReplaceExtensions)
- (NSString *)stringByReplacingStringsFromDictionary:(NSDictionary *)dict;
@end

@implementation NSString (ReplaceExtensions)
- (NSString *)stringByReplacingStringsFromDictionary:(NSDictionary *)dict
{
    NSMutableString *string = [self mutableCopy];
    for (NSString *target in dict) {
       [string replaceOccurrencesOfString:target withString:[dict objectForKey:target] 
               options:0 range:NSMakeRange(0, [string length])];
    }
    return [string autorelease];
}
@end
Georg Fritzsche