小总结,希望以后能用的着
1.转换成oc再截取
let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let ocStr = NSString(string: str)
//截取从开始到指定位置的字符串(to: 截取开始到此下标范围的字符串)
let startOCStr = ocStr.substring(to: 4)
print(startOCStr) //ABCD
//截取从指定位置到结尾的字符串(from: 截取从该下标到结尾的字符串)
let endOCStr = ocStr.substring(from: 15)
print(endOCStr) //PQRSTUVWXYZ
//截取指定范围的字符串(location:从该位置开始截取, length:截取的长度)
let rangOCStr = ocStr.substring(with: NSRange.init(location: 1, length: 7))
print(rangOCStr) //BCDEFGH
2.纯swift方法
let swiftStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
//截取从开始到指定位置的字符串(to: 截取范围 swiftStr.startIndex:起点, offsetBy:起点偏移距离)
let startSwiftStr = swiftStr.substring(to: swiftStr.index(swiftStr.startIndex, offsetBy: 5))
print(startSwiftStr) //ABCDE
//截取从指定位置到结尾的字符串(from: 截取范围)
//此处是从下标为2字符开始截取到末尾(swiftStr.startIndex:起点, offsetBy:起点偏移距离)
let endSwiftStr = swiftStr.substring(from: swiftStr.index(swiftStr.startIndex, offsetBy: 2))
print(endSwiftStr) //CDEFGHIJKLMNOPQRSTUVWXYZ
//此处是从尾巴开始算起的倒数第2个字符开始截取到末尾(swiftStr.endIndex:末尾, offsetBy:末尾偏移长度)
let end2SwiftStr = swiftStr.substring(from: swiftStr.index(swiftStr.endIndex, offsetBy: -2))
print(end2SwiftStr) //YZ
//截取指定位置的字符串(Range<String.Index>带尖括号的是泛型)
let startIndex = swiftStr.index(swiftStr.startIndex, offsetBy: 1)
let endIndex = swiftStr.index(swiftStr.startIndex, offsetBy: 9)
let range = startIndex..<endIndex
let rangSwiftStr = swiftStr.substring(with: range)
print(rangSwiftStr) //BCDEFGHI