Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse NSString text

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?

like image 955
SimplyKiwi Avatar asked Jul 16 '11 20:07

SimplyKiwi


1 Answers

Block version.

NSString *myString = @"abcdefghijklmnopqrstuvwxyz"; NSMutableString *reversedString = [NSMutableString stringWithCapacity:[myString length]];  [myString enumerateSubstringsInRange:NSMakeRange(0,[myString length])                               options:(NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences)                           usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {                             [reversedString appendString:substring];                         }];  // reversedString is now zyxwvutsrqponmlkjihgfedcba 
like image 137
Jano Avatar answered Oct 02 '22 16:10

Jano