How to get the number of elements that have a string value

advertisements

How to get the count of elements present in array that contains only string @"one".

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

How to get the count of array which contains one in it.


Many ways to go:

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

Use blocks:

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

Use loop:

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

Use NSCountedSet:

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

Use NSPredicate:(as EridB suggested)

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

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

Check answers here for more detail.