5
var password : string = "F36fjueEA5lo903"

i need separte this character by character.

something like this.

var 1character : string = "F"
var 2character : string = "3"
var 3character : string = "6"

. . .

PD: I am a novice

2
  • While you can convert the string to an array of characters, it’s worth asking the question “what are you trying to do?”. Often, iterating over the string using map, find, slicing etc gets you what you need without having to do that conversion. Commented Apr 28, 2015 at 23:34
  • Compare stackoverflow.com/questions/25921204/… Commented Apr 29, 2015 at 1:28

2 Answers 2

6

You can do it with:

let characters = Array(password)

With this you have an array of the characters in the String. You can assign it to other variables if you want to.

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

Comments

1

While you can do it like Jacobson showed you in his answer(perfectly fine), you shouldn't save the letters manually in own variables. Because you often don't know the length of the password. So what you could do is iterating over your chars:

for letter in yourString{
    //do something with the current letter
    var yourCurrentLetter = letter
    println(yourCurrentLetter)//a then s, d, f etc.
}

5 Comments

Well, yea I said you can assign it to other variables purely because it's unknown what he wants to do with it ;p
@JacobsonTalom Your answer is perfectly fine.(+1 from me) But most of the time if the OP is a beginner, they don't know about the possibilities to make things more simple.
True, I was thinking of adding some examples with map, but I think your example with a for-loop would be easier to understand. On the other hand, I thought arrays are one of the first basic things a beginner would learn, hence why I showed him how to make an array :) (and thanks)
If you want to for…in over the string, there’s no need to convert it to an array first, strings conform to SequenceType too.
np - I agree with you that chances are the questioner doesn’t really need “the third character”, they need to achieve some other goal and chances are for…in or map or find etc will do the trick

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.