检测数组中的条目重复多少次。数组如下:
"Family:0",
"Family:0",
"Family:0",
"Gold:3",
"Gold:3"
因此返回的条目数应该是3和2。应该怎么实现?我试过的代码(当然没实现):
int occurrences = 0;
int i=0;
for(NSString *string in arrTotRows){
occurrences += ([string isEqualToString:[arrTotRows objectAtIndex:indexPath.section]]); //certain object is @"Apple"
i++;
}
使用NSCountedSet实现,将所有的对象添加为计数设置,使用countForObject:
方法算出重复次数。
例子:
NSArray *names = [NSArray arrayWithObjects:@"Family:0", @"Family:0", @"Gold:3", @"Gold:3", nil];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];
for (id item in set)
{
NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
}
输出:
Name=Gold:3, Count=2
Name=Family:0, Count=2