截取前 n 个字符:
let str = "Hello, Swift!"
let prefix = str.prefix(5)
print(prefix) // "Hello"
截取后 n 个字符:
let str = "Hello, Swift!"
let suffix = str.suffix(6)
print(suffix) // "Swift!"
截取指定范围内的字符:
let str = "Hello, Swift!"
let range = str.index(str.startIndex, offsetBy: 7)..<str.endIndex
let subString = str[range]
print(subString) // "Swift!"
截取从某个位置到末尾的字符:
let str = "Hello, Swift!"
let index = str.index(str.startIndex, offsetBy: 7)
let subString = str[index...]
print(subString) // "Swift!"
从最后一个指定“.”字符开始截取,到字符串结束:
let str = "http://www.free.com/346345647457.png"
if let dotIndex = str.lastIndex(of: ".") {
let fileExtension = str[dotIndex+1..<str.endIndex]
print(fileExtension) // "png"