DAS
DAS

Reputation: 1941

Detect number of different strings in Array

Basically I need a function which counts the amount of different values in an array and one other function to give me the actual count of each different value in my array.

I have an Array which contains a changing amount of values:

Array = (This, This, This, This, Is, Is, Is, Is, Is, It, It, It, It)

I want to make a list view, each section should contain the different categories like:

This
- Element 1
- Element 2
- ...
Is
- Element 1
- ...
It
- Element 1
- ...

So I need the number 3 for my number of sections and the number of child-elements for each section.

How can I achieve that? Is there a better way than a for-statement with counting indexes for each section?

Thank you!

Upvotes: 0

Views: 92

Answers (2)

John Smith
John Smith

Reputation: 2022

First, make o copy of your array, to work with.

  1. To count different values, remove all duplicates from the copied array, and copiedArray.count will tell you what you need. (search on your own how to remove duplicates).
  2. To get the actual count of each group: you have the copied array already without duplicates, so make a for loop within the copied array:

    for (NSString *stringer in copiedArrayWithoutDuplicates){

       int counter = 0;
       for(NSString *iniStr in initialArrayWithDuplicates){
          if([stringer isEqualToString: iniStr]){
              counter++;
          }
       }
       NSLog(@"string %@ was detected %i times", stringer, counter);
    }
    

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385870

Add each array element to an NSCountedSet. Then the count of the set is the number of distinct objects you added, and you can use countForObject: to ask the set how many there are of each distinct object.

Upvotes: 4

Related Questions