Replace multiple groups of characters in an NSString
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&" wi开发者_开发问答thString:@" "];
NSString *result2 = [result stringByReplacingOccurrencesOfString:@"</B>" withString:@" "];
NSString *result3 = [result2 stringByReplacingOccurrencesOfString:@"gt;" withString:@" "];
return [result3 stringByReplacingOccurrencesOfString:@" Description " withString:@""];
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
In modern Objective C with ARC:
-(NSString*)stringByReplacingStringsFromDictionary:(NSDictionary*)dict
{
NSMutableString *string = self.mutableCopy;
for(NSString *key in dict)
[string replaceOccurrencesOfString:key withString:dict[key] options:0 range:NSMakeRange(0, string.length)];
return string.copy;
}
精彩评论