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



Ironic... This question came up in a job interview I had a couple weeks ago. The following NSString category will work to reverse a string, and in my limited tests, it works with accents, mathematical symbols, and Korean characters:

- (NSString *) stringByReversingSelf {
	NSMutableString * r = [NSMutableString stringWithString:self];
	NSUInteger len = [r length];
	NSUInteger mid = floor(len/2);
	for(int i = 0; i < mid; i++) {
		NSRange fr = NSMakeRange(i,1);
		NSRange lr = NSMakeRange(len-i-1,1);
		NSString * f = [r substringWithRange:fr];
		NSString * l = [r substringWithRange:lr];
		[r replaceCharactersInRange:fr withString:l];
		[r replaceCharactersInRange:lr withString:f];
	}
	return r;
}

Here's the output of my extremely limited tests: (attached as a .png screenshot so that the encoding doesn't get messed up)



Cheers,

Dave

On Dec 31, 2008, at 8:51 AM, Michael Ash wrote:

On Wed, Dec 31, 2008 at 4:28 AM, Peter Hudson <email@hidden> wrote:
I have been using the following for a while across a number of languages
without problems.



NSString *s = @"Hello"; unsigned int length = [s length]; unsigned int index = length - 1;

NSMutableArray *ma = [NSMutableArray  array];

while( index < UINT_MAX )
{
      NSRange rng = NSMakeRange( index, 1 );
      [ma  addObject:[s  substringWithRange:rng]];
      --index;
}

NSString *reversed = [ma  componentsJoinedByString:@""];
NSLog(@"reversed : %@",reversed);

I'm rather surprised, as this will fail on something as simple as an accented e using a separate combining character, let alone more complex constructs.

Mike
_______________________________________________

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 (Gabe Shahbazian) (From: Peter Hudson <email@hidden>)
 >Re: Reversing a String (Gabe Shahbazian) (From: "Michael Ash" <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.