这是我编辑和检查的解决方案:
- (NSString *)generateRandString {
NSString *alphabet = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789";
NSMutableString *s;
NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
do
{
s = [NSMutableString stringWithCapacity:5];
for (NSUInteger i = 0U; i < 5; i++)
{
u_int32_t r = arc4random() % [alphabet length];
unichar c = [alphabet characterAtIndex:r];
[s appendFormat:@"%C", c];
}
}
while ([s rangeOfCharacterFromSet:set].location == NSNotFound);
return s;
}
我还实施了 Dan Dyer 建议的解决方案(它显然比我的要好)。我的实现可能并不完美(我多次使用相同的功能,而不是为它创建一个单独的函数,但我相信这对你来说并不难实现),但它的工作原理与 Dan 提出的完全一样。
NSString *alphabet = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789";
NSMutableString *s = [NSMutableString string];
NSCharacterSet *set = [NSCharacterSet decimalDigitCharacterSet];
NSString *digits = @"0123456789";
for (NSUInteger i = 0U; i < 4; i++)
{
u_int32_t r = arc4random() % [alphabet length];
unichar c = [alphabet characterAtIndex:r];
[s appendFormat:@"%C", c];
}
if ([s rangeOfCharacterFromSet:set].location == NSNotFound)
{
u_int32_t r = arc4random() % [digits length];
unichar c = [digits characterAtIndex:r];
[s appendFormat:@"%C", c];
}
else
{
u_int32_t r = arc4random() % [alphabet length];
unichar c = [alphabet characterAtIndex:r];
[s insertString:[NSString stringWithFormat:@"%C", c] atIndex:arc4random() % s.length];
}