删除NSArray中所有重复的字符串 [英] Remove all strings with duplicates in an NSArray

查看:70
本文介绍了删除NSArray中所有重复的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何在Objective-C中实现这一点.

I am trying to figure out how to implement this in Objective-C.

我想删除在数组中多次出现的NSArray中的字符串.

I want to remove the strings in an NSArray that have appear more than once in the array.

最后,我希望有一个数组,该数组仅包含数组中的唯一行(这意味着不仅删除重复项,而且删除与重复项匹配的原始字符串.)

At the end I want to have an array that only has the unique lines in an array (meaning that not just the duplicates are deleted but also the original string that matches the duplicates.)

例如,如果您具有以下数组:

For example if you had the following array:

NSArray *array = [NSArray arrayWithObjects:@"bob", @"frank", @"sarah", @"sarah", @"fred", @"corey", @"corey", nil];

我希望新数组看起来像这样:

I would want the new array to look like this:

@"bob", @"frank", @"fred"

推荐答案

使用 @Caleb 建议在NSCountedSet中添加一种名为-objectsWithCount:,的方法,该方法已在此处实现:

@Caleb suggested adding a method to NSCountedSet called -objectsWithCount:,, which I've implemented here:

@interface NSCountedSet (JRCountedSetAdditions)

- (NSArray *) objectsWithCount:(NSUInteger) count;

@end

@implementation NSCountedSet (JRCountedSetAdditions) 

- (NSArray *) objectsWithCount:(NSUInteger) count {
   NSMutableArray *array = [NSMutableArray array];
   for(id obj in self) {
      if([self countForObject:obj] == count) {
        [array addObject:obj];
      }  
   }
   return [array copy];
}

@end

完成后,您只需一行:

NSArray *finalArray = [[NSCountedSet setWithArray:yourArray] objectsWithCount:1];

顺便说一句,这与类型无关,因此可以与任何Objective-C对象一起使用. :-)

这篇关于删除NSArray中所有重复的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆