2012-05-12 75 views

回答

11

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

會給你一個隨機大寫字符。

+0

不應該是** arc4random_uniform(26)**?由於arc4random_uniform(25)的最大值是24(根據[手冊頁](https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man3/arc4random_uniform.3.html) ),'A'+ 24是'Y'。 – Gyfis

0

將所有大寫字母存儲在數組中,並使用rand()或arcg4rand()從0-25生成隨機數,然後分別檢索對象和隨機編號索引。

+1

爲什麼你會打擾所有的數組操作,當你可以做'A'+ your_random_number ... – verdesmarald

+0

是啊..你說得對 – Allamaprabhu

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]; 

希望回答這是你想要的。 :-)

阿爾貝託