Dipankar Choudhary
Dipankar Choudhary

Reputation: 11

how to merge two arrays in objective c one element at a time?

i have two NSarrays called value and operator. i want to merge them into a third array called equation such that the first element of equation is from value, second from operators, third from value and so on. how can i do it.

Upvotes: 0

Views: 139

Answers (2)

Literphor
Literphor

Reputation: 498

I would use an enumerator here since you can use it to control how and when you iterate through array and loop it through until all elements are consumed

Something like:

NSEnumerator *valueEnumerator = [values objectEnumerator];
NSEnumerator *operatorsEnumerator = [value objectEnumerator];
id anObject;

do{
    if(anObject = [valueEnumerator nextObject])
        [equation.addObject:anObject];
    if(anObject = [operatorsEnumerator nextObject])
        [equation.addObject:anObject];
}while(equation.count != (values.count + operators.count))

Upvotes: -1

Balu
Balu

Reputation: 8460

try like this

 for(int i=0;i<[arrValues count];i++){
        [arrResult addObject:[arrValues objectAtIndex:i]];
        if(i<[arrOperators count])
        [arrResult addObject:[arrOperators objectAtIndex:i]];
    }

Upvotes: 2

Related Questions