Convert Swift string to array

IosArraysSwiftString

Ios Problem Overview


How can I convert a String "Hello" to an Array ["H","e","l","l","o"] in Swift?

In Objective-C I have used this:

NSMutableArray *characters = [[NSMutableArray alloc] initWithCapacity:[myString length]];
for (int i=0; i < [myString length]; i++) {
    NSString *ichar  = [NSString stringWithFormat:@"%c", [myString characterAtIndex:i]];
    [characters addObject:ichar];
}

Ios Solutions


Solution 1 - Ios

It is even easier in Swift:

let string : String = "Hello 🐶🐮 🇩🇪"
let characters = Array(string)
println(characters)
// [H, e, l, l, o,  , 🐶, 🐮,  , 🇩🇪]

This uses the facts that

  • an Array can be created from a SequenceType, and
  • String conforms to the SequenceType protocol, and its sequence generator enumerates the characters.

And since Swift strings have full support for Unicode, this works even with characters outside of the "Basic Multilingual Plane" (such as ) and with extended grapheme clusters (such as , which is actually composed of two Unicode scalars).


Update: As of Swift 2, String does no longer conform to SequenceType, but the characters property provides a sequence of the Unicode characters:

let string = "Hello 🐶🐮 🇩🇪"
let characters = Array(string.characters)
print(characters)

This works in Swift 3 as well.


Update: As of Swift 4, String is (again) a collection of its Characters:

let string = "Hello 🐶🐮 🇩🇪"
let characters = Array(string)
print(characters)
// ["H", "e", "l", "l", "o", " ", "🐶", "🐮", " ", "🇩🇪"]

Solution 2 - Ios

Edit (Swift 4)

In Swift 4, you don't have to use characters to use map(). Just do map() on String.

let letters = "ABC".map { String($0) }
print(letters) // ["A", "B", "C"]
print(type(of: letters)) // Array<String>

Or if you'd prefer shorter: "ABC".map(String.init) (2-bytes )

Edit (Swift 2 & Swift 3)

In Swift 2 and Swift 3, You can use map() function to characters property.

let letters = "ABC".characters.map { String($0) }
print(letters) // ["A", "B", "C"]
Original (Swift 1.x)

Accepted answer doesn't seem to be the best, because sequence-converted String is not a String sequence, but Character:

$ swift
Welcome to Swift!  Type :help for assistance.
  1> Array("ABC")
$R0: [Character] = 3 values {
  [0] = "A"
  [1] = "B"
  [2] = "C"
}

This below works for me:

let str = "ABC"
let arr = map(str) { s -> String in String(s) }

Reference for a global function map() is here: http://swifter.natecook.com/func/map/

Solution 3 - Ios

There is also this useful function on String: components(separatedBy: String)

let string = "1;2;3"
let array = string.components(separatedBy: ";")
print(array) // returns ["1", "2", "3"]

Works well to deal with strings separated by a character like ";" or even "\n"

Solution 4 - Ios

Updated for Swift 4

Here are 3 ways.

//array of Characters
let charArr1 = [Character](myString)

//array of String.element
let charArr2 = Array(myString)

for char in myString {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

//array of String
var strArr = myString.map { String($0)}

Swift 3

Here are 3 ways.

let charArr1 = [Character](myString.characters)
let charArr2 = Array(myString.characters)
for char in myString.characters {
  //char is of type Character
}

In some cases, what people really want is a way to convert a string into an array of little strings with 1 character length each. Here is a super efficient way to do that:

var strArr = myString.characters.map { String($0)}

Or you can add an extension to String.

extension String {
   func letterize() -> [Character] {
     return Array(self.characters)
  }
}

Then you can call it like this:

let charArr = "Cat".letterize()

Solution 5 - Ios

For Swift version 5.3 its easy as:

let string = "Hello world"
let characters = Array(string)

print(characters)

// ["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]

Solution 6 - Ios

for the function on String: components(separatedBy: String)

in Swift 5.1

have change to:

string.split(separator: "/")

Solution 7 - Ios

An easy way to do this is to map the variable and return each Character as a String:

let someText = "hello"

let array = someText.map({ String($0) }) // [String]

The output should be ["h", "e", "l", "l", "o"].

Solution 8 - Ios

Martin R answer is the best approach, and as he said, because String conforms the SquenceType protocol, you can also enumerate a string, getting each character on each iteration.

let characters = "Hello"
var charactersArray: [Character] = []

for (index, character) in enumerate(characters) {
    //do something with the character at index
    charactersArray.append(character)
}

println(charactersArray)

Solution 9 - Ios

    let string = "hell0"
    let ar = Array(string.characters)
    print(ar)

Solution 10 - Ios

In Swift 4, as String is a collection of Character, you need to use map

let array1 = Array("hello") // Array<Character>
let array2 = Array("hello").map({ "\($0)" }) // Array<String>
let array3 = "hello".map(String.init) // Array<String>

Solution 11 - Ios

You can also create an extension:

var strArray = "Hello, playground".Letterize()

extension String {
    func Letterize() -> [String] {
        return map(self) { String($0) }
    }
}

Solution 12 - Ios

func letterize() -> [Character] {
	return Array(self.characters)
}

Solution 13 - Ios

Suppose you have four text fields otpOneTxt, otpTwoTxt, otpThreeTxt, otpFourTxt and a string getOtp.

let getup = "5642"
let array = self.getOtp.map({ String($0) })
                
otpOneTxt.text = array[0] //5
otpTwoTxt.text = array[1] //6
otpThreeTxt.text = array[2] //4
otpFourTxt.text = array[3] //2

Solution 14 - Ios

let str = "cdcd"
let characterArr = str.reduce(into: [Character]()) { result, letter in
    result.append(letter)
}
print(characterArr)
//["c", "d", "c", "d"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMr.KLDView Question on Stackoverflow
Solution 1 - IosMartin RView Answer on Stackoverflow
Solution 2 - IosdevxoulView Answer on Stackoverflow
Solution 3 - IosFrédéric AddaView Answer on Stackoverflow
Solution 4 - IosScottyBladesView Answer on Stackoverflow
Solution 5 - IosAli HamadView Answer on Stackoverflow
Solution 6 - IosFat PandaView Answer on Stackoverflow
Solution 7 - IosatoliteView Answer on Stackoverflow
Solution 8 - IosAlberto BarreraView Answer on Stackoverflow
Solution 9 - IosWilliam HuView Answer on Stackoverflow
Solution 10 - Iosonmyway133View Answer on Stackoverflow
Solution 11 - IosfabrizioMView Answer on Stackoverflow
Solution 12 - IosPiotr PszczółkowskiView Answer on Stackoverflow
Solution 13 - IosDavender VermaView Answer on Stackoverflow
Solution 14 - IosManishaView Answer on Stackoverflow