views:

65

answers:

2

I want to get a character from somewhere inside an NSString. I want the result to be an NSString.

This is the code I use to get a single character at index it:

[[s substringToIndex:i] substringToIndex:1]

Is there a better way to do it?

+2  A: 

This will also retrieve a character at index i as an NSString, and you're only using an NSRange struct rather than an extra NSString.

NSString * newString = [s substringWithRange:NSMakeRange(i, 1)];
Robot K
+2  A: 

Your suggestion only works for simple characters like ASCII. NSStrings store unicode and if your character is several unichars long then you could end up with gibberish. Use

- (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)index;

if you want to determine how many unichars your character is. I use this to step through my strings to determine where the character borders occur.

Being fully unicode able is a bit of work but depends on what languages you use. I see a lot of asian text so most characters spill over from one space and so it's work that I need to do.

No one in particular
The documentation page for this method has a useful code fragment to adjust any range to start and stop at the Unicode boundaries. http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
JeremyP