How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = \"Hello, world!\"
var firstChar = string[
I think that a fast answer for get the first character could be:
let firstCharacter = aString[aString.startIndex]
It's so much elegant and performance than:
let firstCharacter = Array(aString.characters).first
But.. if you want manipulate and do more operations with strings you could think create an extension..here is one extension with this approach, it's quite similar to that already posted here:
extension String {
var length : Int {
return self.characters.count
}
subscript(integerIndex: Int) -> Character {
let index = startIndex.advancedBy(integerIndex)
return self[index]
}
subscript(integerRange: Range) -> String {
let start = startIndex.advancedBy(integerRange.startIndex)
let end = startIndex.advancedBy(integerRange.endIndex)
let range = start..
}
BUT IT'S A TERRIBLE IDEA!!
The extension below is horribly inefficient. Every time a string is accessed with an integer, an O(n) function to advance its starting index is run. Running a linear loop inside another linear loop means this for loop is accidentally O(n2) — as the length of the string increases, the time this loop takes increases quadratically.
Instead of doing that you could use the characters's string collection.