Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separating a string in swift

Tags:

swift

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

like image 407
Sebastian Castro Avatar asked Apr 28 '15 23:04

Sebastian Castro


People also ask

How do I separate words in a string Swift?

Swift – Split a String by Character Separator To split a String by Character separator in Swift, use String. split() function. Call split() function on the String and pass the separator (character) as argument. split() function returns a String Array with the splits as elements.

How do you split a string into two parts in Swift?

Swift String split() The split() method breaks up a string at the specified separator and returns an array of strings.

How do I convert a string to an array in Swift?

To convert a string to an array, we can use the Array() intializer syntax in Swift. Here is an example, that splits the following string into an array of individual characters. Similarly, we can also use the map() function to convert it. The map() function iterates each character in a string.

How do I remove a character from a string in Swift?

Swift String remove() The remove() method removes a character in the string at the specified position.


2 Answers

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.

like image 128
Eendje Avatar answered Oct 23 '22 12:10

Eendje


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.
}
like image 30
Christian Avatar answered Oct 23 '22 11:10

Christian