gpt4 book ai didi

swift - 在数组索引上创建随机字符串

转载 作者:行者123 更新时间:2023-11-28 13:00:36 25 4
gpt4 key购买 nike

func randomStringWithLength (len : Int) -> NSString {

let answer : NSString = ArrAnswer.objectAtIndex(0) as! NSString
let letters : NSString = answer
print(letters)
let randomString : NSMutableString = NSMutableString(capacity: len)

for (var i=0; i < len; i++){
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))

}

return randomString
}

我已经试过了,某些后者在每次或某些时候都会丢失到转换后的字符串中,两次或三次打印后者。

最佳答案

我不确定你到底需要什么。如果你需要随机化字符串中的字符,你可以使用这样的东西

import Foundation
let str = "abcdef"

// returns string with random order of characters
func randomize(str: String)->String {
var chars = str.characters.map{ $0 }
let c = UInt32(chars.count)
if c < 2 { return str}

for i in 0..<(c - 1) {
let j = arc4random_uniform(c)
if i != j {
swap(&chars[Int(i)], &chars[Int(j)])
}
}
return chars.reduce("", combine: { (str, c) -> String in
str + String(c)
})
}
for i in 0...10 {
print(randomize(str))
}
/* prints

dcbeaf
edcabf
cebadf
adcbef
dacbef
dceabf
eacbdf
adebcf
adcbef
bedcaf
daebcf

*/

关于swift - 在数组索引上创建随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33993120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com