如何获取字符串值为1的元素的数量

问题描述:

如何获取数组中只包含字符串@“one”的元素的数量。如何获取字符串值为1的元素的数量

NSMutableArray *array = [[NSMutableArray alloc]initWithObject:@"one",@"one",@"two",@"one",@"five",@"one",nil]; 

如何获取其中包含一个数组的数量。

+0

的可能的复制[目的-C:?计数的次数在阵列中出现的对象(http://*.com/questions/4833992/objective-c-count-the-number-of-times-an-object-occurrence-in-an-array) – Manishankar

+0

只是使用NSPredicate,简单而优化的方式... –

+1

还没试过呢,但键值编码及其特殊键(@count等)可能适用于... ...? – uliwitness

很多路要走:

NSMutableArray *array = [[NSMutableArray alloc]initWithObject:@"one",@"one",@"two",@"one",@"five",@"one",nil]; 

使用块:

NSInteger occurrenceCount = [[array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {return [obj isEqual:@"one"];}] count]; 

使用循环:

int occurrenceCount = 0; 
for(NSString *str in array){ 
    occurrenceCount += ([string isEqualToString:@"one"]?1:0); 
} 

使用NSCountedSet

NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array]; 
NSLog(@"Occurrences of one: %u", [countedSet countForObject:@"one"]); 

使用NSPredicate:(如EridB建议)

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains %@", 
          @"one"]; 

NSInteger occurrenceCount = [array filteredArrayUsingPredicate:predicate].count; 

检查答案here了解更多详情。

有提到从那些另一溶液

// Query to find elements which match 'one' 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains %@", 
          @"one"]; 

// Use the above predicate on your array 
// The result will be a `NSArray` so from there we count the elements on this array 
NSInteger count = [array filteredArrayUsingPredicate:predicate].count; 

// Prints out number of elements 
NSLog(@"%li", (long)count); 

NSArray *array = @[@"one",@"one",@"two",@"one",@"five",@"one"]; 
    NSPredicate *searchCountString= [NSPredicate predicateWithFormat:@"SELF contains %@",@"one"]; 
    NSInteger count = [array filteredArrayUsingPredicate:searchCountString].count; 
    NSLog(@"%ld",(long)count);