iOS 生成随机字符串 从指定字符串随机产生n个长度的新字符串

  • 随机字符串 - 生成指定长度的字符串
-(NSString *)randomStringWithLength:(NSInteger)len {
     NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    
    for (NSInteger i = 0; i < len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length])]];
    }
    return randomString;
}
  • 指定字符串随机生成指定长度的新字符串
-(NSString *)randomStringWithLength:(NSInteger)len String:(NSString *)letters {
    
    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];
    
    for (NSInteger i = 0; i < len; i++) {
        [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length])]];
    }
    return randomString;
}
//调用方法
-(NSString *)generateCard{
    //HXMF   123456789TJQK
    NSString *color =[self randomStringWithLength:1 String:@"HXMF"];
    NSString *number = [self randomStringWithLength:1 String:@"123456789TJQK"];
    return [NSString stringWithFormat:@"%@%@",color,number];
}

转载于:https://www.cnblogs.com/qqcc1388/p/6732562.html

你可能感兴趣的:(swift)