从NSCharacterSet生成随机字符串

时间:2014-09-24 12:28:23

标签: objective-c nscharacterset

我有以下NSCharacterSet,并希望生成一个对该字符集有效的随机字符串。

NSMutableCharacterSet *characterSet = [NSMutableCharacterSet alphanumericCharacterSet];

[characterSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];

[NSCharacterSet characterSetWithCharactersInString:]从字符串中生成字符集。我想要一种相反的方法。像[NSString stringWithCharacterSet:]

这样的东西

1 个答案:

答案 0 :(得分:3)

我不认为NSCharacterSet是存储有效字符列表的最佳方式,因为它没有提供方便的方法来获取其长度或访问特定索引处的字符。请改用NSString

+ (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];

}