2

I have the following NSCharacterSet and want to generate a random string valid for that character set.

NSMutableCharacterSet *characterSet = [NSMutableCharacterSet alphanumericCharacterSet];

[characterSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];

[NSCharacterSet characterSetWithCharactersInString:] produces a character set out of a string. I want a method that does the opposite. Something like [NSString stringWithCharacterSet:]

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • Well, you'd pretty much have to generate a random `unichar` value and test it's membership in the set. You could perhaps speed things along by first doing a "census" with haveMemberInPlane, to find what ranges are possible. – Hot Licks Sep 24 '14 at 12:35
  • You have to do something more than say "gimme the code". – Hot Licks Sep 24 '14 at 15:47

1 Answers1

3

I don't think NSCharacterSet is the best way to store the list of valid characters as it doesn't provide convenient methods to get its length or access a character at a particular index. Use NSString instead:

+ (NSString *)randomStringFromCharacters:(NSString *)chars
                                ofLength:(NSUInteger)length
{
    unichar str[length];
    for (NSUInteger i = 0; i < length; i++)
        str[i] = [chars characterAtIndex:arc4random() % [chars length]];

    return [NSString stringWithCharacters:str length:length];

}
shim
  • 9,289
  • 12
  • 69
  • 108
Droppy
  • 9,691
  • 1
  • 20
  • 27
  • And if one *had* to start with a character set, one could spin through the set once to build the list of valid characters, then select from that list. – Hot Licks Sep 24 '14 at 15:48