替换NSString中的多个字符组 [英] Replace multiple groups of characters in an NSString
本文介绍了替换NSString中的多个字符组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在一个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&" withString:@" "];
NSString *result2 = [result stringByReplacingOccurrencesOfString:@"</B>" withString:@" "];
NSString *result3 = [result2 stringByReplacingOccurrencesOfString:@"gt;" withString:@" "];
return [result3 stringByReplacingOccurrencesOfString:@" Description " withString:@""];
推荐答案
我认为SDK中没有任何内容,但你至少可以使用一个类别,所以你可以写这样的东西:
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
在带有ARC的现代Objective C中:
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;
}
这篇关于替换NSString中的多个字符组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文