如何从ios中的给定字符串生成随机非重复(不重复相同的字母)字母数字字符串?
答案 0 :(得分:4)
以下函数将获取一个字符串并将其随机化,通常每次输入字符串中的每个字符只有一次:
- (NSString *)randomizeString:(NSString *)str
{
NSMutableString *input = [str mutableCopy];
NSMutableString *output = [NSMutableString string];
NSUInteger len = input.length;
for (NSUInteger i = 0; i < len; i++) {
NSInteger index = arc4random_uniform((unsigned int)input.length);
[output appendFormat:@"%C", [input characterAtIndex:index]];
[input replaceCharactersInRange:NSMakeRange(index, 1) withString:@""];
}
return output;
}
答案 1 :(得分:2)
-(NSString *)randomStringWithLength: (int) len
{
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
for (int i=0; i<len; i++)
{
[randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
}
return randomString;
}`