Unfortunately, this is not correct; -[NSString characterAtIndex:] returns a unichar, which is not a char. In addition, it will give odd results for composed characters. Depending on what you want, you might be able to use rangeOfComposedCharacterAtIndex:.

I'd also use NSMutableString instead of a stack buffer of chars, since this looks like a buffer overflow (unless I'm missing something):

I think this is definitely the way to go. Something like this (untested, typed into Mail):

- (NSString*) reversedString
{
        unsigned len = [self length];
        NSMutableString* reversed = [NSMutableString stringWithCapacity:len];
        
        unsigned charIdx = len;
        while( charIdx > 0 ) {
NSRange charRng = [self rangeOfComposedCharacterSequenceAtIndex: (charIdx - 1)];
                [reversed appendString:[self substringWithRange:charRng]];
                charIdx = charRng.location;
        }

        return reversed;
}

Naturally this will be horribly inefficient, as it creates a new object for every composed character sequence, but the logic is likely what an end-user would expect a reversed string to look like.

If you ever actually needed to optimize the string reversal you could drop down to using a reasonably sized unichar buffer and "getCharacters:inRange:" to do it in batches. I'm not sure how one would best optimize the composed character sequences calculations, but probably checking against +[NSCharacterSet nonBaseCharacterSet] would be good enough.

~Martin
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to