Replace multiple character groups in NSString

I want to replace several different groups of characters in one NSString. I am currently doing this with several repetitive methods, however I hope there is a way to do this in one way:

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

NSString *result3 = [result2 stringByReplacingOccurrencesOfString:@"gt;" withString:@" "];
return [result3 stringByReplacingOccurrencesOfString:@" Description  " withString:@""];
+3
source share
1 answer

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

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

... using 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;
}
+6
source

Source: https://habr.com/ru/post/1765248/


All Articles