0
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
}

i have already try this, Some latter missing in to converted string at every time or some time print a latter twice or thrice time.

2 Answers 2

1

i am not sure what exactly do you need. if you need randomize characters in string, you can use something like this

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

*/
Sign up to request clarification or add additional context in comments.

Comments

1

I think this is the best way to do it, unless otherone has another way, you may need to adapt this code for your necesities:

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

1 Comment

i want to convert index of string like "Frodo" i don't get random index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.