How to extract first n characters of an NSString

- by

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


If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.