Objective-C:计算一个对象在数组中出现的次数?

发布于 2024-11-09 16:49:50 字数 311 浏览 1 评论 0原文

我需要执行我认为是基本功能的功能,但我找不到任何有关如何执行此操作的文档。请帮忙!

我需要计算某个对象在数组中出现的次数。请参阅示例:

array = NSArray arrayWithObjects:@"Apple", @"Banana", @"Cantaloupe", @"Apple", @"DragonFruit", @"Eggplant", @"Apple", @"Apple", @"Guava",nil]retain];

如何迭代数组并计算找到字符串@“Apple”的次数?

任何帮助表示赞赏!

I need to perform what I feel is a basic function but I can't find any documentation on how to do it. Please help!

I need to count how many times a certain object occurs in an array. See example:

array = NSArray arrayWithObjects:@"Apple", @"Banana", @"Cantaloupe", @"Apple", @"DragonFruit", @"Eggplant", @"Apple", @"Apple", @"Guava",nil]retain];

How can I iterate through the array and count the number of times it finds the string @"Apple"?

Any help is appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

不知在何时 2024-11-16 16:49:50

另一种解决方案,使用块(工作示例):

NSInteger occurrences = [[array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {return [obj isEqual:@"Apple"];}] count];
NSLog(@"%d",occurrences);

One more solution, using blocks (working example):

NSInteger occurrences = [[array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {return [obj isEqual:@"Apple"];}] count];
NSLog(@"%d",occurrences);
策马西风 2024-11-16 16:49:50

正如@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]; ...

As @bbum said, use an NSCounted set. There is an initializer thet will convert an array directly into a counted set:

    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 output:
(D [1], M [1], E [1], A [1], B [3], X [2], C [1])

Just access items:

count = [countedSet countForObject: anObj]; ...
小帐篷 2024-11-16 16:49:50

一个简单而具体的答案:

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 的答案也很好。使用块的迭代速度更快,但在这种特定情况下,元素很少,我想没有明显的增益。不过我会用它:)

A Simple and specific answer:

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's answer is quite good too. Iteration is faster with blocks but in this specific case with so few elements I guess there is no apparent gain. I would use that though :)

最笨的告白 2024-11-16 16:49:50

使用 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];

Use an NSCountedSet; it'll be faster than a dictionary and is designed to solve exactly that problem.

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];
厌味 2024-11-16 16:49:50

刚刚遇到这个很老的问题。我建议使用 NSCountedSet

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

Just came across this pretty old question. I'd recommend using a NSCountedSet:

NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:array];
NSLog(@"Occurrences of Apple: %u", [countedSet countForObject:@"Apple"]);
浅浅淡淡 2024-11-16 16:49:50

我鼓励您将它们放入字典(Objective C 版本的地图)中。字典的键是对象,值应该是计数。当然它应该是一个 MutableDictionary。如果未找到该项目,则添加该项目并将计数设置为 1。

I would encourage you to put them into a Dictionary (Objective C's version of a map). The key to the dictionary is the object and the value should be the count. It should be a MutableDictionary of course. If the item is not found, add it and set the count to 1.

在梵高的星空下 2024-11-16 16:49:50
- (int) numberOfOccurrencesForString:(NSString*)needle inArray:(NSArray*)haystack {
    int count = 0;

    for(NSString *str in haystack) {
        if([str isEqualToString:needle]) {
            count++;
        }
    }

    return count;
}
- (int) numberOfOccurrencesForString:(NSString*)needle inArray:(NSArray*)haystack {
    int count = 0;

    for(NSString *str in haystack) {
        if([str isEqualToString:needle]) {
            count++;
        }
    }

    return count;
}
天暗了我发光 2024-11-16 16:49:50

我赞成罗布的回答,但我想添加一些代码,希望能有所帮助。

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

I up-voted Rob's answer, but I wanted to add some code that I hope will be of some assistance.

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]);
}
雨落星ぅ辰 2024-11-16 16:49:50

如果数组按照问题陈述中的方式排序,那么您不需要使用字典。

您只需执行 1 次线性扫描,并在看到 2 个连续元素相同时增加计数器,即可更有效地找到唯一元素的数量。

字典解是 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

If the array is sorted as in the problem statement then you don't need to use a dictionary.

You can find the number of unique elements more efficiently by just doing 1 linear sweep and incrementing a counter when you see 2 consecutive elements being the same.

The dictionary solution is O(nlog(n)), while the linear solution is O(n).

Here's some pseudo-code for the linear solution:

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
清晰传感 2024-11-16 16:49:50

完整代码参考@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);
}

谢谢。

the complete code with reference to @bbum and @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);
}

Thank you.

触ぅ动初心 2024-11-16 16:49:50

如果您希望它更通用,或者您想对数组中的相等/不同对象进行计数,请尝试以下操作:

签署“!”计算不同值。如果您想要相同值,请删除“!”

  int count = 0;
  NSString *wordToCheck = [NSString string];
  for (NSString *str in myArray) {
    if( ![str isEqualToString:wordToCheck] ) {
      wordToCheck = str;
      count++;
    }
  }

希望这对社区有帮助!

我已经用它在 uitableview 中添加了正确数量的部分!

If you want it more generic, or you want to count equals/different objects in array, try this:

Sign "!" count DIFFERENT values. If you want SAME values, remove "!"

  int count = 0;
  NSString *wordToCheck = [NSString string];
  for (NSString *str in myArray) {
    if( ![str isEqualToString:wordToCheck] ) {
      wordToCheck = str;
      count++;
    }
  }

hope this helps the community!

I've used it to add correct number of sections in uitableview!

诗化ㄋ丶相逢 2024-11-16 16:49:50

你可以这样做,

 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

You can do this way,

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

The result is like : A 1

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文