我需要执行我认为的基本功能,但我找不到任何关于如何操作的文档。请帮忙!
我需要计算某个对象在数组中出现的次数。见例:
array = NSArray arrayWithObjects:@"Apple", @"Banana", @"Cantaloupe", @"Apple", @"DragonFruit", @"Eggplant", @"Apple", @"Apple", @"Guava",nil]retain];
如何遍历数组并计算找到字符串@“Apple”的次数?
感谢任何帮助!
答案 0 :(得分:19)
使用块(工作示例)的另一个解决方案:
NSInteger occurrences = [[array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {return [obj isEqual:@"Apple"];}] count];
NSLog(@"%d",occurrences);
答案 1 :(得分:17)
正如@bbum所说,使用NSCounted集。有一个初始化器,它会将一个数组直接转换为一个计数集:
NSArray *array = [[NSArray alloc] initWithObjects:@"A", @"B", @"X", @"B", @"C", @"D", @"B", @"E", @"M", @"X", nil];
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];
NSLog(@"%@", countedSet);
NSLog输出: (D [1],M [1],E [1],A [1],B [3],X [2],C [1])
只需访问项目:
count = [countedSet countForObject: anObj]; ...
答案 2 :(得分:15)
一个简单而具体的答案:
int occurrences = 0;
for(NSString *string in array){
occurrences += ([string isEqualToString:@"Apple"]?1:0); //certain object is @"Apple"
}
NSLog(@"number of occurences %d", occurrences);
PS:Martin Babacaev的回答也很好。块的迭代速度更快,但在这种特殊情况下,元素很少,我猜没有明显的增益。我会用那个:))
答案 3 :(得分:15)
使用NSCountedSet
;它会比字典更快,旨在解决这个问题。
NSCountedSet *cs = [NSCountedSet new];
for(id anObj in someArray)
[cs addObject: anObj];
// then, you can access counts like this:
.... count = [cs countForObject: anObj]; ...
[cs release];
答案 4 :(得分:7)
刚刚遇到这个相当古老的问题。我建议使用NSCountedSet
:
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];
NSLog(@"Occurrences of Apple: %u", [countedSet countForObject:@"Apple"]);
答案 5 :(得分:4)
我鼓励你把它们放入一个字典(Objective C的地图版本)。字典的关键是对象,值应该是计数。它当然应该是一个MutableDictionary。如果找不到该项,请添加该项并将计数设置为1.
答案 6 :(得分:3)
- (int) numberOfOccurrencesForString:(NSString*)needle inArray:(NSArray*)haystack {
int count = 0;
for(NSString *str in haystack) {
if([str isEqualToString:needle]) {
count++;
}
}
return count;
}
答案 7 :(得分:2)
我对Rob的回答表示赞同,但我想添加一些代码,希望能提供一些帮助。
NSArray *array = [[NSArray alloc] initWithObjects:@"A", @"B", @"B", @"B", @"C", @"D", @"E", @"M", @"X", @"X", nil];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
for(int i=0; i < [array count]; i++) {
NSString *s = [array objectAtIndex:i];
if (![dictionary objectForKey:s]) {
[dictionary setObject:[NSNumber numberWithInt:1] forKey:s];
} else {
[dictionary setObject:[NSNumber numberWithInt:[dictionary objectForKey:s] intValue]+1 forKey:s];
}
}
for(NSString *k in [dictionary keyEnumerator]) {
NSNumber *number = [dictionary objectForKey:k];
NSLog(@"Value of %@:%d", k, [number intValue]);
}
答案 8 :(得分:2)
如果数组按问题语句排序,则不需要使用字典。
当您看到2个连续元素相同时,只需执行1次线性扫描并递增计数器,就可以更有效地找到唯一元素的数量。
字典解决方案是O(nlog(n)),而线性解决方案是O(n)。
这是线性解决方案的一些伪代码:
array = A,B,B,B,B,C,C,D,E,M,X,X #original array
array = array + -1 # array with a dummy sentinel value to avoid testing corner cases.
# Start with the first element. You want to add some error checking here if array is empty.
last = array[0]
count = 1 # you have seen 1 element 'last' so far in the array.
for e in array[1..]: # go through all the elements starting from the 2nd one onwards
if e != last: # if you see a new element then reset the count
print "There are " + count + " " + last elements
count = 1 # unique element count
else:
count += 1
last = e
答案 9 :(得分:2)
参考@bbum和@Zaph
的完整代码NSArray *myArray = [[NSArray alloc] initWithObjects:@"A", @"B", @"X", @"B", @"C", @"D", @"B", @"E", @"M", @"X", nil];
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:myArray];
for (NSString *item in countedSet) {
int count = [countedSet countForObject: item];
NSLog(@"the String ' %@ ' appears %d times in the array",item,count);
}
谢谢。
答案 10 :(得分:0)
如果你想要它更通用,或者你想在数组中计算equals /不同的对象,试试这个:
签署“!”计算不同值。如果您想要 SAME 值,请删除“!”
int count = 0;
NSString *wordToCheck = [NSString string];
for (NSString *str in myArray) {
if( ![str isEqualToString:wordToCheck] ) {
wordToCheck = str;
count++;
}
}
希望这有助于社区!
我用它在uitableview中添加了正确数量的部分!
答案 11 :(得分:0)
你可以这样做,
NSArray *array = [[NSArray alloc] initWithObjects:@"A", @"B", @"X", @"B", @"C", @"D", @"B", @"E", @"M", @"X", nil];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:array];
NSArray *uniqueStates = [[orderedSet set] allObjects];
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];
for(int i=0;i<[uniqueStates count];i++){
NSLog(@"%@ %d",[uniqueStates objectAtIndex:i], [countedSet countForObject: [uniqueStates objectAtIndex:i]]);
}
结果如下:A 1