如何在Objective-C中生成随机大写字符

问题描述 投票:2回答:3

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

ios objective-c ios5
3个回答
11
投票

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


0
投票

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


0
投票
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];
© www.soinside.com 2019 - 2024. All rights reserved.