Search code examples
iosobjective-cnsarray

Separate array of strings by several arrays


I have an array, that consist of following strings:

[NSString stringByAppendingFormat:@"<p style=\"padding-left:20px;margin-bottom:-10px;\"><i>%@%@%@%@</i></p>",
                         wrappingBy, pack1, pack2, strFirmName];

For example, it have 200 different strings. First parameter - wrappingBy, may have several different names. For example - box, tube, bag, etc.

What i want is, to enumerate through that array, and create different arrays depending on that name. So, if my array consist of 50 strings start from box, 50 strings start from tube, and 100 strings start from bag i want 3 different arrays.

Is there any easy way to achieve that?


Solution

  • Try this:

    Let's say you have the array of strings:

    NSArray *arr=@[@"box3523sfgsg",@"boxsdfsdf3",@"bag!@$#",@"!@@4bag",@"tube@#$FR",@"tubeASAD"];
    

    In your case, the above array is filled with following string

    [NSString stringByAppendingFormat:@"<p style=\"padding-left:20px;margin-bottom:-10px;\"><i>%@%@%@%@</i></p>",
                             wrappingBy, pack1, pack2, strFirmName];
    

    Now add the wrappingBy param to the array everytime you add the above string to the array, and make sure you don;t add duplicates to the array. YOu can check the duplicates before adding them to the array.

    and in your case, you would do

            NSMutableArray *arrayNAme=[[NSMutableArray alloc]init];
    
            //make arrayName mutable
            if (![arrayNAme containsObject: wrappingBy]) {
                 [arrayNAme addObject: wrappingBy];
            }
    

    you will get arrayNAMe contain following:

          arrayNAme=@[@"box",@"bag",@"tube"];
    

    Now search the main array string if it contains the wrapingBy names or not, if YES, add them to an array and add that array to the dicitonary:

        NSMutableDictionary *myDictionary=[[NSMutableDictionary alloc]init];
        for( NSString *nameString in arrayNAme) {
           NSMutableArray *strnArray=[[NSMutableArray alloc]init];
           for (NSString *str in arr)
           {
               if([str containsString:nameString])
               {
                [strnArray addObject:str];
                [myDictionary setValue:strnArray forKey:nameString];
               }
           }
        }
    

    At the end you have the dictionary:

        {
        bag =     (
            "bag!@$#",
            "!@@4bag"
        );
        box =     (
            box3523sfgsg,
            boxsdfsdf3
        );
        tube =     (
            "tube@#$FR",
            tubeASAD
        );
    }
    

    Now you can get each key value and store them in a separate array.