Objective-c – print reverse of a string

ipadiphoneobjective c

I am writing a program which prints the reverse of a string in a textfield, taking input text from the other textfield. When I press enter after entering text into one textfield the result(reverse) should be dispalyed in the other text field.

I have tried like this, but am getting weird results.

.h file:

#import <UIKit/UIKit.h>


@interface reverseVC : UIViewController {

    UITextField *textEntered;
    UITextField *textDisplay;

}
@property (nonatomic,retain) IBOutlet UITextField *textDisplay;
@property (nonatomic,retain) IBOutlet UITextField *textEntered;

- (NSMutableArray*) stringReverse;
- (IBAction) enter;

@end

.m file

- (NSMutableArray *) stringReverse
{

    NSString *value = textEntered.text;
    NSArray *tempArray = [[[NSArray alloc] initWithObjects:value,nil] autorelease];

    NSMutableArray *arr = [[[NSMutableArray alloc] init] autorelease];


    for (int i=[tempArray count]-1; i>=0; i--)
    {
        [arr addObject:[tempArray objectAtIndex:i]];
        NSLog(@"the object is:%c",arr);
    }

    return arr;
}
-(IBAction)enter
{
   textDisplay.text = [NSString stringWithFormat:@"%c",[self stringReverse]];
}

Earlier got warnings like SIG_ABT and EXE_BAD_ACCESS before placing nil and autorelease in array initialisations. Now the warnings are solved but results undesiredly.

Where am I going wrong?

Best Answer

You insert the NSString object in your array. Its count is 1. You have to go from the end of the string to the beginning and append the character to a new string. You ca do it like this:

-(NSString*)reverseString:(NSString*)string {
    NSMutableString *reversedString;
    int length = [string length];
    reversedString = [NSMutableString stringWithCapacity:length];

    while (length--) {
            [reversedString appendFormat:@"%C", [string characterAtIndex:length]];
    }

    return reversedString;
}
Related Topic