如何在Array中循环并添加重复项

时间:2012-08-10 19:28:08

标签: objective-c ios loops

我有一个包含订单数组的字典,其中包含金额和订单Orders = ("3 White Shirts", "8 White Shirts", "4 blue shorts")

我将如何遍历它并添加重复订单的数量,以便结果字符串或数组 Orders = ("11 White Shirts", "4 blue shorts") or myString ="11 White Shirts, 4 blue shorts"

我正在考虑使用某种子字符串来检查产品是否相同但不确定如何捕获从重复订单中添加的正确数量

非常感谢

3 个答案:

答案 0 :(得分:2)

好的,这是一种方法(我能想到的最短的一种):

// 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,请不要忘记发布!

答案 1 :(得分:0)

您需要解析字符串以提取两条信息:订单数量,即数字值,以及项目标识,可以保留为字符串。

使用NSMutableDictionary将项目标识映射到表示当前订单数量的数值,否则检索旧的总计并将当前订单添加到其中,然后更新字典。

最后迭代字典并将每个键值对转换回字符串。

答案 2 :(得分:0)

由于您的数组看起来像包含字符串对象,我会这样做:

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSArray *ordersAsStrings = [NSArray arrayWithObjects:@"7 white shirts", @"4 blue jeans", @"3 white shirts", @"4 blue jeans", nil];
        NSMutableDictionary *combinedQuantities = [NSMutableDictionary new];
        NSMutableArray *combinedOrdersAsStrings = [NSMutableArray new];

        // take each string and break it up into the quantity and the item
        for (NSString *orderAsString in ordersAsStrings) {
            NSInteger scannedQuantity = 0;
            NSString *scannedItem = nil;
            NSScanner *scanner = [NSScanner scannerWithString:orderAsString];
            [scanner scanInteger:&scannedQuantity];
            [scanner scanCharactersFromSet:[[NSCharacterSet illegalCharacterSet] invertedSet] intoString:&scannedItem];

            // if the item is already in combinedOrders
            if ([combinedQuantities.allKeys containsObject:scannedItem] == YES) {
                // update quantity
                NSNumber *existingQuantity = [combinedQuantities objectForKey:scannedItem];
                NSInteger combinedQuantity = existingQuantity.integerValue + existingQuantity.integerValue;
                [combinedQuantities setObject:[NSNumber numberWithInteger:combinedQuantity] forKey:scannedItem];
            } else {
                // otherwise add item
                NSNumber *quantity = [NSNumber numberWithInteger:scannedQuantity];
                [combinedQuantities setObject:quantity forKey:scannedItem];
            }
        }

        // change combined quantities back into strings
        for (NSString *key in combinedQuantities.allKeys) {
            NSNumber *quantity = [combinedQuantities objectForKey:key];
            NSString *orderAsString = [NSString stringWithFormat:@"%ld %@", quantity.integerValue, key];
            [combinedOrdersAsStrings addObject:orderAsString];
        }

        NSLog(@"Combined Orders: %@", combinedOrdersAsStrings);
    }
    return 0;
}