How to get a single NSString character from an NSString

node ninja picture node ninja · Oct 1, 2010 · Viewed 68.5k times · Source

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?

Answer

Kris Markel picture Kris Markel · Oct 1, 2010

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)];