代码来自网络,做了一下修改调整,边界处理等。
新建一个文件StringExtension0.swift 代码如下,打开注释即可(直接粘贴代码,空格没了。。。)。
//
// StringExtension0.swift
//
// Created by mac on 2021/2/20.
//下标操作字符串
/*
测试用例
let aStr = "0123456789";
let str0 = aStr[index: 10]; //获取第几位的字符
let str1 = aStr[19...30]; //从19到30,包含30
let str2 = aStr[15..<56]; //从15到56不包含56
let str3 = aStr[...7]; // 0到7,包含7
let str4 = aStr[9...]; //9到最后,包含9
let str5 = aStr[3,5]; //从3开始,截取5位
let str6 = aStr[from: 14]; //从14开始 同 aStr[14...];
print("str0 \(str0)");
print("str1 \(str1)");
print("str2 \(str2)");
print("str3 \(str3)");
print("str4 \(str4)");
print("str5 \(str5)");
print("str6 \(str6)");
*/
//extension String {
// /// 根据下标获取某个下标字符
// subscript(index index: Int) -> String {
// if index < 0 || index >= self.count{
// return ""
// }
// let startIndex = self.index(self.startIndex, offsetBy: index)
// let endIndex = self.index(startIndex, offsetBy: 1)
// return String(self[startIndex..
// }
// /// 根据range获取字符串 a[1...3]
// subscript(r: ClosedRange) -> String {
// guard r.lowerBound < count else{
// return ""
// }
// let start = index(startIndex, offsetBy: max(r.lowerBound, 0))
// let end = index(startIndex, offsetBy: min(r.upperBound, count - 1))
// return String(self[start...end])
// }
// /// 根据range获取字符串 a[0..<2]
// subscript(r: Range) -> String {
// guard r.lowerBound < count else{
// return ""
// }
// let start = index(startIndex, offsetBy: max(r.lowerBound, 0))
// let end = index(startIndex, offsetBy: min(r.upperBound, count))
// return String(self[start..
// }
// /// 根据range获取字符串 a[...2]
// subscript(r: PartialRangeThrough) -> String {
// let end = index(startIndex, offsetBy: min(r.upperBound, count - 1))
// return String(self[startIndex...end])
// }
// /// 根据range获取字符串 a[5...]
// subscript(r: PartialRangeFrom) -> String {
// guard r.lowerBound < count else{
// return ""
// }
// let start = index(startIndex, offsetBy: max(r.lowerBound, 0))
// let end = index(startIndex, offsetBy: count - 1)
// return String(self[start...end])
// }
// /// 根据range获取字符串 a[..<3]
// subscript(r: PartialRangeUpTo) -> String {
// let end = index(startIndex, offsetBy: min(r.upperBound, count))
// return String(self[startIndex..
// }
// //根据range截取a[3,5] 从3开始截取5位
// subscript(start: Int, count: Int)->String{
// guard start < count else {
// return ""
// }
// let begin = index(startIndex, offsetBy: max(0, start))
// let end = index(startIndex, offsetBy: min(self.count, start + count))
// return String(self[begin..
// }
//
// subscript(from from: Int)->String{
// guard from < count else {
// return ""
// }
// let start = self.index(endIndex, offsetBy: from - count)
// return String(self[start..
// }
//}