文字列@ "one"のみを含む配列に存在する要素の数を取得する方法。文字列値が1の要素の数を取得する方法
NSMutableArray *array = [[NSMutableArray alloc]initWithObject:@"one",@"one",@"two",@"one",@"five",@"one",nil];
1つを含む配列の数を取得する方法。どこへ行く
文字列@ "one"のみを含む配列に存在する要素の数を取得する方法。文字列値が1の要素の数を取得する方法
NSMutableArray *array = [[NSMutableArray alloc]initWithObject:@"one",@"one",@"two",@"one",@"five",@"one",nil];
1つを含む配列の数を取得する方法。どこへ行く
多くの方法:
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-number-of-time-an-object-in-an-array) – Manishankar
NSPredicateを使用して、単純で最適化された方法です... –
これを試していない、キー値コーディングとその特殊キー(@countなど)がこれに対応しています...? – uliwitness