1. 程式人生 > >ios 生成字母加數字的隨機數

ios 生成字母加數字的隨機數

近期專案第三方登入之後預設建立賬號和密碼,就用隨機數生產,這裡只需要傳入你需要幾位的隨機數即可,例如你需要得到8位的隨機數,num就傳入8


好了,廢話少說,簡單Demo如下:


- (NSString *)getRandomStringWithNum:(NSInteger)num
{
    NSString *string = [[NSString alloc]init];
    for (int i = 0; i < num; i++) {
        int number = arc4random() % 36;
        if (number < 10) {
            int figure = arc4random() % 10;
            NSString *tempString = [NSString stringWithFormat:@"%d", figure];
            string = [string stringByAppendingString:tempString];
        }else {
            int figure = (arc4random() % 26) + 97;
            char character = figure;
            NSString *tempString = [NSString stringWithFormat:@"%c", character];
            string = [string stringByAppendingString:tempString];
        }
    }
    return string;
}