在 iPhone 中使用 NSArray 生成随机字符串?
我有一个数组,它有一些数据。现在我想随机更改字符串的位置,这意味着想要将字符串洗入数组中。但我不想更改数组的顺序,我只想更改字符串的顺序,而不更改数组索引位置。
我的实际数组是(
(
first,
second,
third,
fourth
),
(
One,
Two,
Three,
Four
),
(
sample,
test,
demo,
data
)
)
预期结果,
(
(
second,
fourth,
third,
first
),
(
Two,
Four,
One,
Three
),
(
test,
demo,
sample,
data
)
)
请帮助我。
谢谢!
I have one array and it has some data. Now i want to randomly changed the positions of the strings which means, want to shuffle the strings into the array. But i don't want to change the order of the array, I want to changed only order the strings and doesn't changed the array index position.
My actual array is (
(
first,
second,
third,
fourth
),
(
One,
Two,
Three,
Four
),
(
sample,
test,
demo,
data
)
)
Expected result,
(
(
second,
fourth,
third,
first
),
(
Two,
Four,
One,
Three
),
(
test,
demo,
sample,
data
)
)
Please Help me out.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NSIndexSet< /code>
就是为此类任务而设计的。
The
NSIndexSet
is designed for such tasks.这并不难做到。您应该执行以下操作:
将类别添加到 NSArray。以下实现来自 Kristopher Johnson,正如他在 这个问题。
现在您有一个名为 shuffle 的方法,它可以对数组进行洗牌。现在,您可以执行以下操作,以便仅对内部数组中的字符串进行打乱:
现在对内部数组进行打乱。
但请记住,内部数组必须是 NSMutableArrays。否则你将无法洗牌它们。 ;-)
桑德罗·迈耶
It's not that hard to do. You should do the following:
Add a category to NSArray. The following implementation is from Kristopher Johnson as he replied in this question.
Now you have a method called shuffle, which shuffels your array. Now you can do the following so that only the strings in the inner arrays are shuffled:
Now the inner Arrays are shuffled.
But keep in mind, that the inner arrays need to be NSMutableArrays. Else you won't be able to shuffle them. ;-)
Sandro Meier
int 随机索引;
int randomIndex;