this is my first question in stackoverflow! im trying to reverse a string using two arrays in xcode, ive set up the interface,i got a button,a text field and a label. whatever goes into the text field is reversed when the button is touched! i got the code and it seems correct to me on paper,the problem is that when i test the application with for example "HELLO", the content of myArray is "H E" and reverseArray is" O L L". id be grateful if anyone cud help im pretty fed up with tracing this code :((( here is the code:
@interface ViewController ()
@end
@implementation ViewController
@synthesize textField,string1,string2,reverseArray,myArray;
@synthesize Label1;
- (IBAction)Reverse:(UIButton *)sender {
reverseArray=[[NSMutableArray alloc]init];
string1=[[NSString alloc]init];
string2=[[NSString alloc]init];
string1=textField.text;
myArray=[[NSMutableArray alloc]init];
for (int i=0; i<=string1.length-1; i++) {
[myArray insertObject:[[NSString alloc] initWithFormat:@"%c",[string1 characterAtIndex:i]] atIndex:i];
}
for (int j=0; j<=myArray.count-1; j++) {
[reverseArray insertObject:[myArray objectAtIndex:myArray.count-1] atIndex:j];
[myArray removeLastObject];
}
NSLog(@"%@",myArray);
NSLog(@"%@",reverseArray);
For the second loop, you're using myArray.count as the end condition for the "for" loop, but myArray.count is decreasing by one each iteration of the loop because you're removing the last object from myArray each iteration. Think about it:
First iteration: j=0; myArray.count - 1 = 4
Second iteration: j=1; myArray.count - 1 = 3
Third iteration: j=2; myArray.count - 1 = 2
It stops here at the forth iteration because j=3 > myArray.count -1 = 1
Try something like this for the second loop (Note: I'm not in front of xCode right now, so there might be errors in the following block. Take it with a grain of salt):
for( int j = string1.length -1; j >= 0; j-- ) {
[reverseArray addObject:[myArray objectAtIndex:j]];
}