我想知道有没有一种方法可以使用componentsSeperatedByString
中的NSString
删除多个字词/标签?令我印象深刻的唯一想法是调用此方法3次以删除我要删除的所有已定义标记。但这似乎不是那么好的风格。那么有更好的方法吗?
#define REMOVE_TAG_1 @"cs193pspot"
#define REMOVE_TAG_2 @"portrait"
#define REMOVE_TAG_3 @"landscape"
// Formats the subtitle by removing the defined tags
- (NSString *)formatSubtitle:(NSString *)subtitle
{
NSArray *tagsToKeep = [subtitle componentsSeparatedByString:[NSString stringWithFormat:@"%@",REMOVE_TAG_1]];
NSLog(@"%@",[tagsToKeep description]);
return nil;
}
答案 0 :(得分:3)
假设标签是用空格分隔的,我首先将字符串拆分成一个单词数组:
NSArray *arrayOfTagsToFilter = @[ REMOVE_TAG_1, REMOVE_TAG_2, REMOVE_TAG_3 ];
NSArray *allTags = [subtitle componentsSeparatedByString:@" "];
然后使用NSPredicate
过滤数组以获取应删除的数组中的标记:
NSArray *tagsToRemove = [allTags filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF IN %@", arrayOfTagsToFilter]];
NSMutableArray *tagsToKeep = [NSMutableArray arrayWithArray:allTags];
[tagsToKeep removeObjectsInArray:tagsToRemove];