【发布时间】:2012-04-18 23:48:09
【问题描述】:
我看过很多关于如何生成随机字符串的问答。但是,如果我有一个字符串数组(可能是数千个)并且我想抓取一个随机字符串以便每次都向用户呈现不同的字符串,那该怎么办?提前致谢。
wordsArray= [[NSMutableArray alloc] init];
【问题讨论】:
标签: ios nsmutablearray nsmutablestring
我看过很多关于如何生成随机字符串的问答。但是,如果我有一个字符串数组(可能是数千个)并且我想抓取一个随机字符串以便每次都向用户呈现不同的字符串,那该怎么办?提前致谢。
wordsArray= [[NSMutableArray alloc] init];
【问题讨论】:
标签: ios nsmutablearray nsmutablestring
你可以试试:
[wordsArray objectAtIndex:arc4random_uniform([wordsArray count])];
前提是数组不为空。
更新:使用arc4random_uniform() 以获得更好的稳定性。 (感谢理查德)
【讨论】:
arc4random_uniform(),因为它比模数方法更稳定。
arc4random_uniform() will return a uniformly distributed random number less than upper_bound. arc4random_uniform() is recommended over con- structions like 'arc4random() % upper_bound' as it avoids "modulo bias" when the upper bound is not a power of two. 来自 arc4random()_uniform 的手册页