let character = "abcdefghijklmn"
// 獲取字串第一個字元
character[character.startIndex]
character.characters.first
// 獲取字串最後一個字元
let endIndex = character.endIndex // 14
// character[endIndex] // endIndex 直接用endIndex會越界,因為endIndex得到的index是字串的長度,而字串擷取是從下標0開始的,這樣直接用會越界
// 想要獲取字串最後一位
character[character.index(before: character.endIndex)]
character.characters.last
// offset 從指定位置開始,偏移多少位(正負均可)
character[character.index(character.startIndex, offsetBy: 4)]
// 用法跟 character.index(, offsetBy: ) 一樣,只不過這個做了越界校驗,limitedBy填入越界限制.
// 這個方法返回值是個可選的,如果offsetBy的引數大於limitedBy做的限制就會返回nil
let limited = character.index(character.endIndex, offsetBy: -1)
character.index(character.startIndex, offsetBy: 14, limitedBy: limited)
// after 指定位置之後一位
character[character.index(after: character.startIndex)]
character[character.index(after: character.index(character.startIndex, offsetBy: 2))]
// before 指定位置之前的一位
character[character.index(before: character.endIndex)]
character[character.index(before: character.index(character.endIndex, offsetBy: -2))]
// 字串擷取
let range = character.startIndex ..< character.index(character.startIndex, offsetBy: 3)
character[range]
character.substring(with: range)
給String寫個擴充套件
extension String {
public subscript(bounds: CountableRange<Int>) -> String {
let string = self[index(startIndex, offsetBy: bounds.lowerBound) ..< index(startIndex, offsetBy: bounds.upperBound)]
return string
}
public subscript(bounds: CountableClosedRange<Int>) -> String {
let string = self[index(startIndex, offsetBy: bounds.lowerBound) ... index(startIndex, offsetBy: bounds.upperBound)]
return string
}
public subscript(index: Int) -> String {
let character = self[self.index(startIndex, offsetBy: index)]
return String(character)
}
}
用法:
character[3 ..< 14]
character[3 ... 14]
character[1]
character[14]