在IOS上创建随机的Alpha数值。

时间:2021-10-20 23:01:32

i'm java programmer that 'must' move on to obj-C for a while,

我是java程序员,必须继续向objc - c前进一段时间,

i got some confuse when generating random alphanumeric code... here my javacode:

我在生成随机字母数字代码时弄混了……在这里我javacode:

PS: i want to generate code like this :Gh12PU67, AC88pP13, Bk81gH89

PS:我想生成这样的代码:Gh12PU67, AC88pP13, Bk81gH89。

private String generateCode(){
 String code = "";
 Random r = new Random();
 char[] c = new char[]{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

 for(int i = 0; i<4; i++){
  int uplow = r.nextInt(2);
  String temp = ""+ c[r.nextInt(c.length)];
  if(uplow==1)
   code = code + temp.toUpperCase();
 else
   code = code + temp;

 if((i+1)%2==0){
   code += r.nextInt(10);
   code += r.nextInt(10);
 }
}

return code;
}

then i create on OBJ-C

然后我在objc - c上创建。

-(void)generateCode{
    NSString *alphabet  = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY0123456789";
    NSMutableString *s = [NSMutableString stringWithCapacity:4];
    for (NSUInteger i = 0U; i < 4; i++) {
        u_int32_t r = arc4random() % [alphabet length];
        unichar c = [alphabet characterAtIndex:r];
        [s appendFormat:@"%C", c];

    }
    NSLog(@"s-->%@",s);
}

but i got "HpNz" for result AC88pP13 insted that hve pattern String,string, numeric,numeric, lowescase string,numeric,numeric...

但我得到了“HpNz”,结果是AC88pP13,它输入了hve模式字符串、字符串、数字、数字、lowescase字符串、数字、数字……

that case screw my life for 3 days...

那个案子毁了我3天的生活…

2 个解决方案

#1


0  

Your Objective-C code looks good, but (as @Wain correctly said in a comment above), the Java function function contains logic to insert 2 digits after 2 letters, which you have not replicated in the Objective-C method.

您的Objective-C代码看起来不错,但是(正如@Wain在上面的注释中正确地说的),Java函数函数包含了在两个字母后插入两个数字的逻辑,您没有在Objective-C方法中复制。

I would make that logic slightly less obscure and write it as

我会让这个逻辑稍微不那么晦涩,并把它写成。

- (void)generateCode
{
    static NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY";
    static NSString *digits = @"0123456789";
    NSMutableString *s = [NSMutableString stringWithCapacity:8];
    for (NSUInteger i = 0; i < 2; i++) {
        uint32_t r;

        // Append 2 random letters:
        r = arc4random_uniform((uint32_t)[letters length]);
        [s appendFormat:@"%C", [letters characterAtIndex:r]];
        r = arc4random_uniform((uint32_t)[letters length]);
        [s appendFormat:@"%C", [letters characterAtIndex:r]];

        // Append 2 random digits:
        r = arc4random_uniform((uint32_t)[digits length]);
        [s appendFormat:@"%C", [digits characterAtIndex:r]];
        r = arc4random_uniform((uint32_t)[digits length]);
        [s appendFormat:@"%C", [digits characterAtIndex:r]];

    }
    NSLog(@"s-->%@",s);
}

Remark (from the man page): arc4random_uniform(length) is preferred over arc4random() % length, as it avoids "modulo bias" when the upper bound is not a power of two.

注释(从手册页):arc4random_uniform(长度)优于arc4random() %长度,因为它避免了上限为2时的“modulo bias”。

Remark: A more verbatim translation of the Java code code += r.nextInt(10); to Objective-C would be

备注:Java代码代码+= r.nextInt(10)的逐字翻译;objective - c将

r = arc4random_uniform(10);
[s appendString:[@(r) stringValue]];

which creates a NSNumber object @(r) from the random number, and then converts that to a string.

它从随机数中创建一个NSNumber对象@(r),然后将其转换为字符串。

#2


0  

if you want a secure random string you should use this code:

如果您想要一个安全的随机字符串,您应该使用以下代码:

#define ASCII_START_NUMERS 0x30
#define ASCII_END_NUMERS 0x39

#define ASCII_START_LETTERS_A 0x41
#define ASCII_END_LETTERS_Z 0x5A

#define ASCII_START_LETTERS_a 0x61
#define ASCII_END_LETTERS_z 0x5A

-(NSString *)getRandomString:(int)length {
    NSMutableString *result = [[NSMutableString alloc]init];
    while (result.length != length) {
        NSMutableData* data = [NSMutableData dataWithLength:1];
        SecRandomCopyBytes(kSecRandomDefault, 1, [data mutableBytes]);
        Byte currentChar = 0;
        [data getBytes:&currentChar length:1];
        NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if (currentChar > ASCII_START_NUMERS && currentChar < ASCII_END_NUMERS) { // 0 to 0
            [result appendString:s];
            continue;
        }
        if (currentChar > ASCII_START_LETTERS_A && currentChar < ASCII_END_LETTERS_Z) { // A to Z
            [result appendString:s];
            continue;
        }
        if (currentChar > ASCII_START_LETTERS_a && currentChar < ASCII_END_LETTERS_z) { // a to z
            [result appendString:s];
            continue;
        }
    }
    return result;
}

#1


0  

Your Objective-C code looks good, but (as @Wain correctly said in a comment above), the Java function function contains logic to insert 2 digits after 2 letters, which you have not replicated in the Objective-C method.

您的Objective-C代码看起来不错,但是(正如@Wain在上面的注释中正确地说的),Java函数函数包含了在两个字母后插入两个数字的逻辑,您没有在Objective-C方法中复制。

I would make that logic slightly less obscure and write it as

我会让这个逻辑稍微不那么晦涩,并把它写成。

- (void)generateCode
{
    static NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXZY";
    static NSString *digits = @"0123456789";
    NSMutableString *s = [NSMutableString stringWithCapacity:8];
    for (NSUInteger i = 0; i < 2; i++) {
        uint32_t r;

        // Append 2 random letters:
        r = arc4random_uniform((uint32_t)[letters length]);
        [s appendFormat:@"%C", [letters characterAtIndex:r]];
        r = arc4random_uniform((uint32_t)[letters length]);
        [s appendFormat:@"%C", [letters characterAtIndex:r]];

        // Append 2 random digits:
        r = arc4random_uniform((uint32_t)[digits length]);
        [s appendFormat:@"%C", [digits characterAtIndex:r]];
        r = arc4random_uniform((uint32_t)[digits length]);
        [s appendFormat:@"%C", [digits characterAtIndex:r]];

    }
    NSLog(@"s-->%@",s);
}

Remark (from the man page): arc4random_uniform(length) is preferred over arc4random() % length, as it avoids "modulo bias" when the upper bound is not a power of two.

注释(从手册页):arc4random_uniform(长度)优于arc4random() %长度,因为它避免了上限为2时的“modulo bias”。

Remark: A more verbatim translation of the Java code code += r.nextInt(10); to Objective-C would be

备注:Java代码代码+= r.nextInt(10)的逐字翻译;objective - c将

r = arc4random_uniform(10);
[s appendString:[@(r) stringValue]];

which creates a NSNumber object @(r) from the random number, and then converts that to a string.

它从随机数中创建一个NSNumber对象@(r),然后将其转换为字符串。

#2


0  

if you want a secure random string you should use this code:

如果您想要一个安全的随机字符串,您应该使用以下代码:

#define ASCII_START_NUMERS 0x30
#define ASCII_END_NUMERS 0x39

#define ASCII_START_LETTERS_A 0x41
#define ASCII_END_LETTERS_Z 0x5A

#define ASCII_START_LETTERS_a 0x61
#define ASCII_END_LETTERS_z 0x5A

-(NSString *)getRandomString:(int)length {
    NSMutableString *result = [[NSMutableString alloc]init];
    while (result.length != length) {
        NSMutableData* data = [NSMutableData dataWithLength:1];
        SecRandomCopyBytes(kSecRandomDefault, 1, [data mutableBytes]);
        Byte currentChar = 0;
        [data getBytes:&currentChar length:1];
        NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if (currentChar > ASCII_START_NUMERS && currentChar < ASCII_END_NUMERS) { // 0 to 0
            [result appendString:s];
            continue;
        }
        if (currentChar > ASCII_START_LETTERS_A && currentChar < ASCII_END_LETTERS_Z) { // A to Z
            [result appendString:s];
            continue;
        }
        if (currentChar > ASCII_START_LETTERS_a && currentChar < ASCII_END_LETTERS_z) { // a to z
            [result appendString:s];
            continue;
        }
    }
    return result;
}