2012-04-18 40 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