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]