How can I get the nth character of a string? I tried bracket([]
) accessor with no luck.
var string = \"Hello, world!\"
var firstChar = string[
let str = "My String"
String at index
let index = str.index(str.startIndex, offsetBy: 3)
String(str[index]) // "S"
Substring
let startIndex = str.index(str.startIndex, offsetBy: 3)
let endIndex = str.index(str.startIndex, offsetBy: 7)
String(str[startIndex...endIndex]) // "Strin"
First n chars
let startIndex = str.index(str.startIndex, offsetBy: 3)
String(str[..
Last n chars
let startIndex = str.index(str.startIndex, offsetBy: 3)
String(str[startIndex...]) // "String"
str = "My String"
**String At Index **
Swift 2
let charAtIndex = String(str[str.startIndex.advancedBy(3)]) // charAtIndex = "S"
Swift 3
str[str.index(str.startIndex, offsetBy: 3)]
SubString fromIndex toIndex
Swift 2
let subStr = str[str.startIndex.advancedBy(3)...str.startIndex.advancedBy(7)] // subStr = "Strin"
Swift 3
str[str.index(str.startIndex, offsetBy: 3)...str.index(str.startIndex, offsetBy: 7)]
First n chars
let first2Chars = String(str.characters.prefix(2)) // first2Chars = "My"
Last n chars
let last3Chars = String(str.characters.suffix(3)) // last3Chars = "ing"