Swift Range和字符串截取

Range

  • ClosedRange: a...b
  • CountableClosedRange: a...b
  • Range: a..
  • CountRange: a..
  • PartialRangeThrough: ...b
  • PartialRangeFrom: a...
  • PartialRangeUpTo: ..

字符串截取

let str = "123456789"
let start = str.startIndex//表示str的开始位置
let end = str.endIndex//表示str的结束位置
let startOffset = str.index(start, offsetBy: 2)//表示str的开始位置 + 2
let endOffset = str.index(end, offsetBy: -2)//表示str的结束位置 - 2
        
print(str[start])//输出 1 第1个字符
print(str[startOffset])//输出 3 第3个字符
print(str[endOffset])//输出 8 第8个字符(10-2)
print(str[end])//报错!因为实endIndex指向第10个字符,而第10个字符是不存在的

String Extension

    /// 根据下标获取某个下标字符
    subscript(of index: Int) -> String {
        if index < 0 || index >= self.count{
            return ""
        }
        for (i,item) in self.enumerated(){
            if index == i {
                return "\(item)"
            }
        }
        return ""
    }
    /// 根据range获取字符串 a[1...3]
    subscript(r: ClosedRange) -> String {
        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 {
        let start = index(startIndex, offsetBy: max(r.lowerBound, 0))
        let end = index(startIndex, offsetBy: min(r.upperBound, count))
        return String(self[start..) -> String {
        let end = index(startIndex, offsetBy: min(r.upperBound, count - 1))
        return String(self[startIndex...end])
    }
    /// 根据range获取字符串 a[0...]
    subscript(r: PartialRangeFrom) -> String {
        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.. String {
        guard index < count else {
            return ""
        }
        let start = self.index(endIndex, offsetBy: index - count)
        return String(self[start.. String {
        let begin = index(startIndex, offsetBy: max(0, start))
        let end = index(startIndex, offsetBy: min(count, start + count))
        return String(self[begin..

使用

        let str = "0123456789"
        print(str[of: 9])
        print(str[0...9])
        print(str[0..<9])
        
        print(str[0...])
        print(str[1...])
        print(str[...9])
        print(str[..<10])

你可能感兴趣的:(Swift Range和字符串截取)