2013-06-04 209 views
0

如何检查数组中有多少次重复项。我有一个包含重复项目的数组。下面是数组。计算每个值在数组中重复的次数

"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++; 
} 
+0

看到我的答案.... –

回答

2

您可以使用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 
0

NSCountedSet解决了这个问题。将所有字符串与addObject:相加,然后在枚举集合时使用countForObject:获得最终计数。

7
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:yourArray]; 

为获得出现的次数:

int objectCount = [countedSet countForObject:yourQuery]; 

(其中yourQuery是你想获得多重性的对象)。在你的情况,例如:

int objectCount = [countedSet countForObject:@"Family:0"]; 

objectCount应该等于3,因为“家庭:0”是多集的三倍。

+0

是什么yourQuery? –

+0

@iPhoneProgrammatically multiset中的任何对象。例如:''Family:0“',它应该返回3.我已经更新了我的答案。 –

0

请试试这个....

int count = 0; 

for (int i = 0; i < array.count; ++i) { 
    NSString *string = [array objectAtIndex:i]; 
    for (int j = i+1; j < array.count; ++j) { 
     if ([string isEqualToString:[array objectAtIndex:j]]) { 
     count++; 
     } 
    } 
相关问题