如何獲取數組中只包含字符串@「one」的元素的數量。如何獲取字符串值爲1的元素的數量
NSMutableArray *array = [[NSMutableArray alloc]initWithObject:@"one",@"one",@"two",@"one",@"five",@"one",nil];
如何獲取其中包含一個數組的數量。
如何獲取數組中只包含字符串@「one」的元素的數量。如何獲取字符串值爲1的元素的數量
NSMutableArray *array = [[NSMutableArray alloc]initWithObject:@"one",@"one",@"two",@"one",@"five",@"one",nil];
如何獲取其中包含一個數組的數量。
很多路要走:
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);
的可能的複製[目的-C:?計數的次數在陣列中出現的對象(http://stackoverflow.com/questions/4833992/objective-c-count-the-number-of-times-an-object-occurrence-in-an-array) – Manishankar
只是使用NSPredicate,簡單而優化的方式... –
還沒試過呢,但鍵值編碼及其特殊鍵(@count等)可能適用於... ...? – uliwitness