Reverse NSString text

Viewed 45124

I have been googling so much on how to do this, but how would I reverse a NSString? Ex:hi would become: ih

I am looking for the easiest way to do this.

Thanks!

@Vince I made this method:

- (IBAction)doneKeyboard {

// first retrieve the text of textField1
NSString *myString = field1.text;
NSMutableString *reversedString = [NSMutableString string];
NSUInteger charIndex = 0;
while(myString && charIndex < [myString length]) {
    NSRange subStrRange = NSMakeRange(charIndex, 1);
    [reversedString appendString:[myString substringWithRange:subStrRange]];
    charIndex++;
}
// reversedString is reversed, or empty if myString was nil
field2.text = reversedString;
}

I hooked up that method to textfield1's didendonexit. When I click the done button, it doesn't reverse the text, the UILabel just shows the UITextField's text that I entered. What is wrong?

19 Answers
  • NSString into char utf32 (always 32 bits (unsigned int))
  • Reverse
  • char utf32 into NSString

+ (NSString *)reverseString3:(NSString *)str {
    unsigned int *cstr, buf, len = [str length], i;  
    cstr  = (unsigned int *)[str cStringUsingEncoding:NSUTF32LittleEndianStringEncoding];
    for (i=0;i < len/2;i++) buf = cstr[i], cstr[i] = cstr[len -i-1], cstr[len-i-1] = buf;
    return [[NSString alloc] initWithBytesNoCopy:cstr length:len*4 encoding:NSUTF32LittleEndianStringEncoding freeWhenDone:NO];
}

Example : Apple_is  --->  si_elppA

We can also achieve the reverse string as follows.

NSString *originalString = @"Hello";
NSString *reverseString;
for (NSUInteger index = originalString.length; index > 0; index--) {
    char character = [originalString characterAtIndex:index];
    reverseString = [reverseString stringByAppendingString:[NSString stringWithFormat:@"%c", character]];
}

or

NSString *originalString = @"Hello";
NSString *reverseString;
for (NSUInteger index = originalString.length; index > 0; index--) {
   char *character = [originalString characterAtIndex:index];
   reverseString = [reverseString stringByAppendingString:[NSString stringWithFormat:@"%s", character]];
}
Related