2

componentsSeperatedByString我想知道有没有使用in删除多个单词/标签的好方法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;
}
4

1 回答 1

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];
于 2013-02-28T16:59:47.470 回答