在 Cocoa 中生成随机字母数字字符串 [英] Generate a random alphanumeric string in Cocoa

查看:32
本文介绍了在 Cocoa 中生成随机字母数字字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用一个方法,将长度传递给它并让它生成一个随机的字母数字字符串.

I want to call a method, pass it the length and have it generate a random alphanumeric string.

是否有任何实用程序库可能包含大量此类函数?

Are there any utility libraries out there that may have a bunch of these types of functions?

推荐答案

这是一个快速而肮脏的实现.尚未经过测试.

Here's a quick and dirty implementation. Hasn't been tested.

NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

-(NSString *) randomStringWithLength: (int) len {

    NSMutableString *randomString = [NSMutableString stringWithCapacity: len];

    for (int i=0; i<len; i++) {
         [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform([letters length])]];
    }

    return randomString;
}

这篇关于在 Cocoa 中生成随机字母数字字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆