How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = "Hello, world!"
var firstChar = string[0] // Throws error
ERROR: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion
Swift 4
This is probably the best way of solving this problem one-time. You probably want to cast the String as an array first, and then cast the result as a String again. Otherwise, a Character will be returned instead of a String.
Example
String(Array("HelloThere")[1])
will return "e" as a String.(Array("HelloThere")[1]
will return "e" as a Character.Swift does not allow Strings to be indexed like arrays, but this gets the job done, brute-force style.
Swift 3: another solution (tested in playground)
Usage:
Swift's
String
type does not provide acharacterAtIndex
method because there are several ways a Unicode string could be encoded. Are you going with UTF8, UTF16, or something else?You can access the
CodeUnit
collections by retrieving theString.utf8
andString.utf16
properties. You can also access theUnicodeScalar
collection by retrieving theString.unicodeScalars
property.In the spirit of
NSString
's implementation, I'm returning aunichar
type.The swift string class does not provide the ability to get a character at a specific index because of its native support for UTF characters. The variable length of a UTF character in memory makes jumping directly to a character impossible. That means you have to manually loop over the string each time.
You can extend String to provide a method that will loop through the characters until your desired index
Get & Set Subscript (String & Substring) - Swift 4.2
Swift 4.2, Xcode 10
I based my answer off of @alecarlson's answer. The only big difference is you can get a
Substring
or aString
returned (and in some cases, a singleCharacter
). You can alsoget
andset
the subscript. Lastly, mine is a bit more cumbersome and longer than @alecarlson's answer and as such, I suggest you put it in a source file.Extension:
You can also convert String to Array of Characters like that:
This is the way to get char at specified index in constant time.
The example below doesn't run in constant time, but requires linear time. So If You have a lot of searching in String by index use the method above.