2012-04-18 39 views
0

我已經看到了很多q & a關於如何生成隨機字符串。但是,如果我有一串字符串(可能是數千),並且我想要抓取一個隨機字符串,那麼每次都會向用戶呈現不同的字符串?提前致謝。在NSMutableString中查找一個隨機字符串

wordsArray= [[NSMutableArray alloc] init]; 

回答

4

你可以試試:

[wordsArray objectAtIndex:arc4random_uniform([wordsArray count])]; 

提供的數組不爲空。

更新:使用arc4random_uniform()更好的穩定性。 (謝謝理查德)

+0

改爲使用'arc4random_uniform()',因爲它比模量方法更穩定。 – 2012-04-18 23:52:07

+0

@ RichardJ.RossIII謝謝理查德。是什麼讓它更穩定? – sooper 2012-04-18 23:54:47

+0

'arc4random_uniform()將返回小於upper_bound的均勻分佈的隨機數 。建議arc4random_uniform()超過類似'arc4random()%upper_bound'的結構,因爲它避免了「模偏差」 ,當上限不是2的冪時。 ''arc4random()_uniform](http://www.unix.com/man-page/freebsd/3/arc4random_uniform/)的手冊頁' – 2012-04-19 00:01:06