【问题标题】:Find a random string in NSMutableString在 NSMutableString 中查找随机字符串
【发布时间】:2012-04-18 23:48:09
【问题描述】:

我看过很多关于如何生成随机字符串的问答。但是,如果我有一个字符串数组(可能是数千个)并且我想抓取一个随机字符串以便每次都向用户呈现不同的字符串,那该怎么办?提前致谢。

wordsArray= [[NSMutableArray alloc] init];

【问题讨论】:

    标签: ios nsmutablearray nsmutablestring


    【解决方案1】:

    你可以试试:

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

    前提是数组不为空。

    更新:使用arc4random_uniform() 以获得更好的稳定性。 (感谢理查德)

    【讨论】:

    • 改用arc4random_uniform(),因为它比模数方法更稳定。
    • @RichardJ.RossIII 谢谢理查德。是什么让它更稳定?
    • 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 的手册页
    • 嗨,Sooper,这是要返回一个值吗?我一定不能完全正确地使用。如果可以,请更新。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    相关资源
    最近更新 更多