Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character Array to string in Swift

Tags:

arrays

swift

The output of the [Character] Array currently is:

["E", "x", "a", "m", "p", "l", "e"] 

It should be:

Example 

It could be that " is in the array, like this: """. That output should be ".

Thank you!

like image 554
Petravd1994 Avatar asked Nov 14 '16 20:11

Petravd1994


People also ask

How do you convert an array of characters to a string Swift?

To convert an array to string in Swift, call Array. joined() function.

How do you declare a character array in Swift?

that is the way to get a nice unicode character array in Swfit: var charArray: Array<Character> = Array(count: 100, repeatedValue: "?")

How do you split a string into characters in Swift?

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.


Video Answer


2 Answers

The other answer(s) cover the case where your array is one of String elements (which is most likely the case here: since you haven't supplied us the type of the array, we could use Swift own type inference rules to speculatively infer the type to be [String]).

In case the elements of your array are in fact of type Character, however, you could use the Character sequence initializer of String directly:

let charArr: [Character] = ["E", "x", "a", "m", "p", "l", "e"] let str = String(charArr) // Example 

W.r.t. your comment below: if your example array is, for some reason, one of Any elements (which is generally not a good idea to use explicitly, but sometimes the case when recieving data from some external source), you first need to perform an attempted conversion of each Any element to String type, prior to concenating the converted elements to a single String instance. After the conversion, you will be working with an array of String elements, in which case the methods shown in the other answers will be the appropriate method of concenation:

// e.g. using joined() let arr: [Any] = ["E", "x", "a", "m", "p", "l", "e"] let str = arr.flatMap { $0 as? String }.joined() print(str) // example 

You could naturally also (attempt to) convert from Any to Character elements, but even in this case you would have to go via String instances, which means that for the [Any] case, the joined() alternative above is to prefer over the one below:

let arr: [Any] = ["E", "x", "a", "m", "p", "l", "e"] let str = String(arr.flatMap { ($0 as? String)?.characters.first }) print(str) // example 
like image 186
dfrib Avatar answered Sep 24 '22 12:09

dfrib


Just use joined() with default "" separator:

let joinedString = ["E", "x", "a", "m", "p", "l", "e"].joined() 
like image 28
vadian Avatar answered Sep 23 '22 12:09

vadian