在ios中生成随机字母数字字符串

时间:2013-10-28 12:45:51

标签: ios random

如何从ios中的给定字符串生成随机非重复(不重复相同的字母)字母数字字符串?

2 个答案:

答案 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;
}`