Evgeniy Kleban Evgeniy Kleban - 3 months ago 9
Objective-C Question

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?

Answer

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:

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

and in your case, you would do

        //make arrayName mutable
        [arrayName addObject: wrappingBy];

At the end you will have the array, and arrayName of equal count:

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 *str in arr) {
        NSMutableArray *strnArray=[[NSMutableArray alloc]init];
        for (NSString *nameString in arrayNAme)
       {
            if([str containsString:nameString])
            {
                [strnArray addObject:str];
                [myDictionary setValue:strnArray forKey:nameString];
            }
        }
    }

At the end you have the dictionary:

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

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