Pages

October 3, 2013

Reverse a NSString chars

How can I reverse a NSString?
Just use this convenient Objective-C method.


/** Reverse all characters of a string.

 @param str String to invert.
 @return Return the reversed string.

 */
+ (NSString *)reverseString:(NSString *)str {
    NSMutableString *reversed = [NSMutableString string];
    NSInteger charIndex = [str length];
    while (charIndex > 0) {
        charIndex--;
        NSRange subRange = NSMakeRange(charIndex, 1);
        [reversed appendString:[str substringWithRange:subRange]];
    }
    return reversed;
}



Download the ready-for-use source file (.m) of Reverse a NSString chars

No comments:

Post a Comment