我有以下NSCharacterSet,并希望生成一个对该字符集有效的随机字符串。
NSMutableCharacterSet *characterSet = [NSMutableCharacterSet alphanumericCharacterSet];
[characterSet formUnionWithCharacterSet:[NSCharacterSet whitespaceCharacterSet]];
[NSCharacterSet characterSetWithCharactersInString:]
从字符串中生成字符集。我想要一种相反的方法。像[NSString stringWithCharacterSet:]
答案 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];
}