Marco Almeida
Marco Almeida

Reputation: 1303

How to separate contents from NSArray into two new one in Objective C?

any one here have an idea how I could separate this array in to 2??

2013-08-25 02:47:47.052 yahoo[11357:c07] (
"",
"1377253260000.33300.0",
"1377253440000.33280.0",
"1377254100000.33280.0",
"1377255600000.33220.0",
"1377257400000.33220.0",
"1377261660000.33200.0",
"1377264000000.33200.0",
"1377264060000.33200.0",
"1377267780000.33200.0",
"1377271260000.33200.0",
"1377273120000.33200.0",
"1377273180000.33200.0",
"1377273240000.33240.0",
""
)

The first NSArray would be with the long numbers and the second with the smaller one including the ".".

So something like: array1 with 1377253260000 and array2 with 33300.0 and so on.

Upvotes: 0

Views: 240

Answers (2)

Ashok
Ashok

Reputation: 6244

Another way..

NSArray *objects = @[
                    @"",
                    @"1377253260000.33300.0",
                    @"1377253440000.33280.0",
                    @"1377254100000.33280.0",
                    @"1377255600000.33220.0",
                    @"1377257400000.33220.0",
                    @"1377261660000.33200.0",
                    @"1377264000000.33200.0",
                    @"1377264060000.33200.0",
                    @"1377267780000.33200.0",
                    @"1377271260000.33200.0",
                    @"1377273120000.33200.0",
                    @"1377273180000.33200.0",
                    @"1377273240000.33240.0",
                    @""
                    ];

NSMutableArray *firstParts = [[NSMutableArray alloc] initWithCapacity:objects.count];
NSMutableArray *secondParts = [[NSMutableArray alloc] initWithCapacity:objects.count];

for (NSString *object in objects)
{
    NSArray *components = [object componentsSeparatedByString:@"."];

    if (components.count > 0) {
        [firstParts addObject:components[0]];
    }
    if (components.count > 1) {
        [secondParts addObject:components[1]];
    }
}
NSLog(@"firstParts = %@", firstParts);
NSLog(@"secondParts = %@", secondParts);

Upvotes: 0

Rob
Rob

Reputation: 437632

There are tons of different ways of doing this. For example, you could do something as simple as find the first period, and add the string up to that period in the first array and everything after in the next array:

NSMutableArray *smallerNumbers = [NSMutableArray array];
NSMutableArray *longNumbers    = [NSMutableArray array];

for (NSString *string in array) {
    NSRange range = [string rangeOfString:@"."];
    if (range.location != NSNotFound) {
        [longNumbers    addObject:[string substringToIndex:range.location - 1]];
        [smallerNumbers addObject:[string substringFromIndex:range.location + 1]];
    } else {
        [longNumbers    addObject:@""];    // or you could insert [NSNull null] or whatever
        [smallerNumbers addObject:@""];
    }
}

Upvotes: 1

Related Questions