• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Reversing a String
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Reversing a String


  • Subject: Re: Reversing a String
  • From: Martin Wierschin <email@hidden>
  • Date: Wed, 31 Dec 2008 00:54:28 -0800

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:
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>)

  • Prev by Date: Storing NSDocument data in packages/bundles
  • Next by Date: Re: Storing NSDocument data in packages/bundles
  • Previous by thread: Re: Reversing a String
  • Next by thread: Re: Reversing a String
  • Index(es):
    • Date
    • Thread