Tag Archives: NSRange

How to explode an NSString into single NSString characters

Say you had an NSString, and you’re interested in each single character. You’d think there’s a method for it, such as getCharactersInRange. Turns out that’s not really helpful, because it delivers unichar characters rather than NSStrings.

To extract single characters as NSStrings, we can use the substringWithRange method like so:

NSString *phrase = @"Complex stuff.";

// split NSString into its characters
for (int i=0; i<phrase.length; i++) {
    NSRange range = NSMakeRange(i, 1);
    NSString *character = [phrase substringWithRange:range];
    NSLog(@"Character is %@", character);


How to extract first n characters of an NSString

We can use substringWithRange for this, which requires us to define a range:

        NSString *something = @"123456789";
        NSRange myRange = NSMakeRange(2, 3);
        something = [something substringWithRange:myRange];

        // something is now 345

You create a range by specifying where the substring should start (the first character is 0, like in an array), then specify how many characters from there you want to use.

To grab just the first character you’d specify a range like this:

        NSString *something = @"123456789";
        NSRange myRange = NSMakeRange(0, 1);
        something = [something substringWithRange:myRange];

        // something is now 1