Tag Archives: NSString

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 turn an NSString into an NSNumber

We can use an NSNumberFormatter for this. It’s a bit like converting an NSString into an NSDate.

Here’s how:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
NSNumber *myNumber = [formatter numberFromString:self.textField.text];

Assuming that we’d like to collect input from a text field (set to accept number pad input only) myNumber will now be an NSNumber instead of text.

How to test for a (null) string in Objective C

I wanted to test if a string has a value when it’s returned from Core Data. So I thought, the right way to do this was to see if it’s equal to nothing, like so:

if ([myString isEqualToString:@""]) {
    // should be empty... but may not be

But to my surprise this didn’t work – because my string was (null) rather than “empty” or nil, which in Objective C are not the same thing.

Instead we can test for the length of this string, and if it returns zero, then we’re sure it’s empty:

    if ([myString length] == 0) {
        // definitely empty!

How to remove the first n characters from an NSString

There’s a convenient method for that by the name of substringFromIndex. This example removes the first character:

    NSString *complete = @"12345";
    NSString *cutOff = [complete substringFromIndex:1];
    NSLog(@"%@", cutOff);
    // cutOff is now 2345

substringFromString takes only one parameter which specifies where to start the new string. The first character is 0 based, like in arrays. The parameter can’t be longer than the original string’s length for obvious reasons.

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