如何计算具有字符串值1的元素

时间:2016-11-04 10:45:58

标签: ios objective-c nsmutablearray

如何获取数组中仅包含字符串@“one”的元素数。

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

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

3 个答案:

答案 0 :(得分:2)

许多方法:

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以获取更多详细信息。

答案 1 :(得分:1)

提到的另一种解决方案

// 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);

答案 2 :(得分:1)

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);