0

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

4

2 回答 2

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;
}
于 2013-10-28T13:07:40.613 回答
3
-(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;
}`
于 2014-08-12T04:19:55.190 回答