How to pick a random character from a string in Objective-C

Imagine we had an NSString consisting of a pool of characters from which we’d like to pick one at random. Say our pool is ABCDEFGHIJKLMNOP, and we want a single character.

Here’s how we can do that:

// pool of characters
NSString *characters = @"ABCDEFGHIJKLMNOP";

// create a random number 
// between 1 and however many characters we have in the pool
uint32_t length = (uint32_t)characters.length;
NSUInteger random = arc4random_uniform(length);

// make a range
NSRange range = NSMakeRange(random, 1);

// pick a random character from the pool
NSString *letter = [characters substringWithRange:range];

The comments speak for themselves. One thing of note is the typecast of characters.length, which is needed to suppress the Xcode warning “implicit conversion loses integer precision”.

Most of the magic is provided by the NSString method substringWithRange.

Leave a Reply

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