Mailing Lists: Apple Mailing Lists

Image of Mac OS face in stamp
 
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Reversing a String



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 (email@hidden)

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/email@hidden

This email sent to email@hidden
References: 
 >Reversing a String (From: "Gabe Shahbazian" <email@hidden>)
 >Re: Reversing a String (From: Ron Fleckner <email@hidden>)
 >Re: Reversing a String (From: "Adam R. Maxwell" <email@hidden>)



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2007 Apple Inc. All rights reserved.