How is the code for separation of single array into two arrays?

江枫思渺然 提交于 2019-12-01 12:59:42

问题


I am getting below response into the nsarray when I used the JSON parsing from my required URL but here I don't like to get 2,1,4,4,6,5,8,7,10,9,12 and 11 in single array I have to get total response into two arrays I mean one array set will consists 2,4,6,8,10 and other array set must be 3,5,7,9 and 11.

So how is the code for separation of single array response into two arrays in iPhone?

"(\n    2,\n    1\n)",
"(\n    4,\n    3\n)",
"(\n    6,\n    5\n)",
"(\n    8,\n    7\n)",
"(\n    10,\n    9\n)",
"(\n    12,\n    11\n)"

回答1:


If you combine every number into one large array, you could feasibly test if each number is even or odd with a simple if-else in a for-in loop. Maybe like this:

-(NSArray*)parseJSONIntoArrays:(NSArray*)array {
    NSMutableArray *evenNumbers = [[NSMutableArray alloc]init];
    NSMutableArray *oddNumbers = [[NSMutableArray alloc]init];

    for (NSNumber *number in array) {
        if (([number intValue] %2) == 0) {
            //even
            [evenNumbers addObject:number];
        }
        else {
            //odd
            [oddNumbers addObject:number];
        }
    }
    return [[NSArray alloc]initWithObjects:evenNumbers, oddNumbers, nil];
}



回答2:


To split an array, you usually need to loop through all of the values and use an IF ELSE structure to decide which array to put the values in. Also, you need to use NSMutableArray instead of NSArray. Something like this:

NSMutableArray *evenNumbers = [NSMutableArray new];
NSMutableArray *oddNumbers = [NSMutableArray new];
for (NSNumber *value in myArray) {
    if ([value intValue] % 2 == 0) {
        [evenNumbers addObject:value];
    } else {
        [oddNumbers addObject:value];
    }
}


来源:https://stackoverflow.com/questions/10793400/how-is-the-code-for-separation-of-single-array-into-two-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!