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

时间:2015-11-30 07:06:07

标签: swift nsmutablearray swift2 nsmutablestring

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
}

我已经尝试过这个, 后者有时会在转换后的字符串中丢失,或者有时会将后者打印两次或三次。

2 个答案:

答案 0 :(得分:1)

我认为这是最好的方法,除非别人有另一种方式,你可能需要根据自己的需要调整这些代码:

let array = ["Frodo", "sam", "wise", "gamgee"]
let randomIndex = Int(arc4random_uniform(UInt32(array.count)))
print(array[randomIndex])

答案 1 :(得分:1)

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

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

*/