如何在我的Objective-C iOS应用中随机生成20个大写字符?
char c = (char)('A' + arc4random_uniform(25))
将所有大写字符存储在数组中,并使用rand()或arcg4rand()从0-25生成随机数,然后分别通过随机数索引检索对象。
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];