【问题标题】:How to generate random uppercase characters in Objective-C如何在 Objective-C 中生成随机大写字符
【发布时间】:2012-05-12 04:54:12
【问题描述】:

如何在我的 Objective-C iOS 应用中随机生成 20 个大写字符?

【问题讨论】:

标签: ios objective-c ios5


【解决方案1】:

char c = (char)('A' + arc4random_uniform(25))

会给你一个随机的大写字符。

【讨论】:

  • 不应该是 arc4random_uniform(26) 吗?由于 arc4random_uniform(25) 的最高数是 24(根据man page),而 'A' + 24 是 'Y'。
【解决方案2】:

将所有大写字符存储在数组中,并使用rand()或arcg4rand()生成0-25的随机数,然后分别检索对象的随机编号索引。

【讨论】:

  • 当你可以做 'A' + your_random_number 时,你为什么还要麻烦所有的数组操作...
【解决方案3】:
NSMutableArray *a = [[NSMutableArray alloc] initWithObjects:@"A", @"B", @"C", @"D", @"E", nil]; // You can add more uppercases here.
int firstRandom = objectAtIndex:arc4random()%[a count];
NSString *s = [[NSString alloc] initWithFormat:@"%@", [a objectAtIndex:firstRandom]];
[a removeObjectAtIndex:firstRandom];
// Avoiding some uppercase repetitions. ;-)
for (int i = 0; i < [a count]; i++) {
    int rndm = objectAtIndex:arc4random()%[a count];
    s += [a objectAtIndex:rndm];
    [a removeObjectAtIndex:rndm];
}
NSLog(@"%@", s);
[a release];
[s release];

希望这是您想要的答案。 :-)

阿尔伯托

【讨论】:

    猜你喜欢
    • 2020-05-01
    • 1970-01-01
    • 2023-03-11
    • 2011-01-09
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    相关资源
    最近更新 更多