好的,这是一种方法(我能想到的最短的方法):
// Assuming that 'orders' is the array in your example
NSMutableDictionary *orderDict = [[NSMutableDictionary alloc] init];
for (NSString *order in orders)
{
// Separate the string into components
NSMutableArray *components = [[order componentsSeparatedByString:@" "] mutableCopy];
// Quantity is always the first component
uint quantity = [[components objectAtIndex:0] intValue];
[components removeObjectAtIndex:0];
// The rest of them (rejoined by a space is the actual product)
NSString *item = [components componentsJoinedByString:@" "];
// If I haven't got the order then add it to the dict
// else get the old value, add the new one and put it back to dict
if (![orderDict valueForKey:item])
[orderDict setValue:[NSNumber numberWithInt:quantity] forKey:item];
else{
uint oldQuantity = [[orderDict valueForKey:item] intValue];
[orderDict setValue:[NSNumber numberWithInt:(oldQuantity+quantity)] forKey:item];
}
}
这会给你一个这样的字典:
{
"White Shirts" = 11;
"blue shorts" = 4;
}
因此,您可以遍历键并生成一个字符串数组,如下所示:
NSMutableArray *results = [[NSMutableArray alloc] initWithCapacity:0];
for (NSString *key in [orderDict allKeys])
{
[results addObject:[NSString stringWithFormat:@"%@ %@", [orderDict valueForKey:key], key]];
}
最后会给你:
(
"11 White Shirts",
"4 blue shorts"
)
PS。如果您不使用 ARC,请不要忘记释放!