-1

I have a String and I want get an Array of the String's Characters.

I can already do it, like this:

var Carr = [Character]()
for c in s.characters {
    Carr.append(c)
}

As you can see, it's not beautiful or efficient.

In Java, I can use char[] sa = s.toCharArray(); to get a char[]. Is there a similarly simple way to do this in Swift?

Alexander
  • 59,041
  • 12
  • 98
  • 151
Eggplant
  • 93
  • 9

2 Answers2

2
let charArray = Array(s.characters)

String.characters is a String.CharacterView. It conforms to BidirectionalCollection, which inherits from Collection, and ultimately Sequence.

Because it conforms to Sequence, it can be used in a for loop, as you showed. But also, it can be used in the initializer of Array that takes a sequence.

Alexander
  • 59,041
  • 12
  • 98
  • 151
0

You are already using the right function:

let yourString = "a string"
let characters = yourString.characters
let count = characters.count

This gives you the collection of characters contained in your string

Ocunidee
  • 1,769
  • 18
  • 20