Reputation: 1227
How to check that how many time items are repeated in array. I am having an array that contains repetitive item. Below is array.
"Family:0",
"Family:0",
"Family:0",
"Gold:3",
"Gold:3"
So, i want in response values 3 and 2 for respective items. How can i achieve that. Hope i made my point clear. If any thing not clear please ask.
Below is my code i tried.
int occurrences = 0;
int i=0;
for(NSString *string in arrTotRows){
occurrences += ([string isEqualToString:[arrTotRows objectAtIndex:indexPath.section]]); //certain object is @"Apple"
i++;
}
Upvotes: 0
Views: 675
Reputation: 6481
please try this....
int count = 0;
for (int i = 0; i < array.count; ++i) {
NSString *string = [array objectAtIndex:i];
for (int j = i+1; j < array.count; ++j) {
if ([string isEqualToString:[array objectAtIndex:j]]) {
count++;
}
}
Upvotes: 0
Reputation: 17535
You can use NSCountedSet for this. Add all your objects to a counted set, then use the countForObject:
method to find out how often each object appears.
Example
NSArray *names = [NSArray arrayWithObjects:@"Family:0", @"Family:0", @"Gold:3", @"Gold:3", nil];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];
for (id item in set)
{
NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
}
Output
Name=Gold:3, Count=2
Name=Family:0, Count=2
Upvotes: 2
Reputation: 7845
NSCountedSet *countedSet = [[NSCountedSet alloc] initWithArray:yourArray];
For getting the number of occurrences:
int objectCount = [countedSet countForObject:yourQuery];
(where yourQuery
is the object whose multiplicity you want to get). In your case, for example:
int objectCount = [countedSet countForObject:@"Family:0"];
and objectCount
should be equal to 3 because "Family:0" is three times in the multiset.
Upvotes: 7
Reputation: 7416
NSCountedSet
solves this very problem. Add all of the strings with addObject:
and then get the final counts with countForObject:
as you enumerate the set.
Upvotes: 0