Swift 4.0(造輪子) 極簡之字符串相應操作(下標法...)

開發(fā)環(huán)境

Mac OS 10.12+ / Xcode 9+ / Swift 4.0

支持環(huán)境

iOS 8+, iPhone & iPad

項目獲取

  • 項目已上傳至GitHub中 ZTSimplifiedString,若要使用,下載后導入您的項目。
  • ZTSimpleString.swift此文件拖入項目之后就可直接使用。

如何使用

通過整數(shù)下標獲取與修改字符串的某個字符

  • 源碼展示
    /// 字符串名[n]: 修改與獲取字符串某個字符
    ///
    /// - Parameter index: 下標整數(shù)
    subscript(index: Int) -> Character {
        set {
            guard index >= 0 && index < self.count else {
                assertionFailure("The subscript has beyond [0,\(self.count-1)]")
                return
            }
            let startIndex = self.startIndex;
            let startPath = self.index(startIndex, offsetBy:index)
            let endPath = self.index(after: startPath)
            let range = startPath ..< endPath
            self.replaceSubrange(range, with: String(newValue))
        }
        get {
            var character:Character = "0"
            guard index < self.count else {
                assertionFailure("The subscript has beyond [0,\(self.count-1)]")
                return character
            }
            let startIndex = self.startIndex;
            let indexPath = self.index(startIndex, offsetBy:index)
            character = self.characters[indexPath]
            return character
        }
    }
  • 使用示例

      var example = "ABCDEFG"
      example[0] = "1" 
      print(example)  //1BCDEFG
      print(example[0]) //輸出1
    

通過整數(shù)范圍下標獲取與修改字符串某個范圍內(nèi)的子串

  • 源碼展示

      /// 字符串名[n,m]:獲取、修改和刪除
      ///
      /// - Parameters:
      ///   - startIndex: 下標整數(shù)
      ///   - endIndex: 下標整數(shù)
      subscript(_ startIndex:Int ,_ endIndex:Int) -> String {
          set {
              var min = startIndex
              var max = endIndex
              guard  (min >= 0 &&  min < self.count) && (max >= 0 &&  max < self.count) else {
                  assertionFailure("The subscript has beyond [0,\(self.count-1)]")
                  return
              }
              if min > max {
                  (min,max) = (max,min)
              }
              let firstIndex = self.startIndex;
              let startPath = self.index(firstIndex, offsetBy:min)
              let endPath = self.index(firstIndex, offsetBy:max)
              let range = startPath ... endPath
              self.replaceSubrange(range, with: newValue)
          }
          get {
              var min = startIndex
              var max = endIndex
              var newString = String()
              guard (min >= 0 &&  min < self.count) && (max >= 0 &&  max < self.count) else {
                  assertionFailure("The subscript has beyond [0,\(self.count-1)]")
                  return newString
              }
              if min > max {
                  (min,max) = (max,min)
              }
              let firstIndex = self.startIndex;
              let startPath = self.index(firstIndex, offsetBy:min)
              let endPath = self.index(firstIndex, offsetBy:max)
              let range = startPath ... endPath
              newString = String(self[range])
              return newString
          }
      }
      
      /// 字符串名[n...m]: 獲取與修改相應的子串
      ///
      /// - Parameter closeRange: 無符號封閉整型范圍
      subscript(_ closeRange:ClosedRange<Int>) -> String {
          set {
              self[closeRange.lowerBound,closeRange.upperBound] = newValue
          }
          get {
              return String(self[closeRange.lowerBound,closeRange.upperBound])
          }
      }
      
      /// 字符串名[n..<m]: 獲取與修改相應的子串
      ///
      /// - Parameter closeRange: 無符號半封閉整型范圍
      subscript(_ subRange:Range<Int>) -> String {
          set {
              self[subRange.lowerBound,subRange.upperBound-1] = newValue
          }
          get {
              return String(self[subRange.lowerBound,subRange.upperBound-1])
          }
      }
    
  • 使用示例

      var example = "ABCDEFG"
    
      print(example[0,1])  //輸出:AB :全封閉區(qū)間
      print(example[1..<3]) //輸出:BC
      print(example[3...5]) //輸出:DEF
      
      example[0,1] = "12"
      example[2..<4] = "34"
      //example[5...7] = "567" //報下標越界error
      example[4...6] = "567"
      print(example) //輸出:1234567
    
      example[0,2] = "" //另類的刪除
      print(example) //輸出:4567
    

通過整數(shù)下標插入字符或字符串

  • 源碼展示

      /// 用對應下標的整數(shù)來插入字符
      ///
      /// - Parameters:
      ///   - newString: 需插入的字符
      ///   - index: 相應下標整數(shù)
      mutating func insert(_ newCharacter:Character, at index:Int) {
          guard index >= 0 && index < self.count else {
              assertionFailure("The subscript has beyond [0,\(self.count-1)]")
              return
          }
          //dealStr[index,index] = newString; //也可以這樣通過下標來插入,但需保持兩個下標相等
          let firstIndex = self.startIndex;
          let indexpath = self.index(firstIndex, offsetBy:index)
          self.insert(newCharacter, at: indexpath)
      }
      /// 用對應下標的整數(shù)來插入字符串
      ///
      /// - Parameters:
      ///   - newString: 需插入的字符串
      ///   - index: 相應下標整數(shù)
      mutating func insert(_ newString:String, at index:Int) {
          guard index >= 0 && index < self.count else {
              assertionFailure("The subscript has beyond [0,\(self.count-1)]")
              return
          }
          //dealStr[index,index] = newString; //也可以這樣通過下標來插入,但需保持兩個下標相等
          let firstIndex = self.startIndex;
          let indexpath = self.index(firstIndex, offsetBy:index)
          self.insert(contentsOf: newString, at: indexpath)
      }
    
  • 使用示例

      var example = "ABCDEFG"
    
      example.insert("0", at: 0)
      print(example) //輸出: 0ABCDEFG
      example.insert("zt", at: example.count-1)
      print(example) //輸出:0ABCDEFztG
    

通過整數(shù)下標刪除字符或字符串

  • 源碼展示

      /// 刪除對應下標整數(shù)的字符
      ///
      /// - Parameter index: 下標整數(shù)
      /// - Returns: 刪除的字符
      mutating func remove(i index: Int) -> Character {
          var character:Character = "0"
          guard index >= 0 && index < self.count else {
              assertionFailure("The subscript has beyond [0,\(self.count-1)]")
              return character
          }
          let indexPath = self.index(self.startIndex, offsetBy: index)
          character = self.remove(at: indexPath)
          return character
      }
      
      /// 給出范圍整數(shù),刪除該范圍的字符串(全封閉區(qū)間)
      ///
      /// - Parameters:
      ///   - startIndex: 初始下標
      ///   - endIndex: 結尾下標
      mutating func remove(from startIndex:Int, to endIndex:Int) {
          var min = startIndex
          var max = endIndex
          guard (min >= 0 &&  min < self.count) && (max >= 0 &&  max < self.count) else {
              assertionFailure("The subscript has beyond [0,\(self.count-1)]")
              return
          }
          if min > max {
              (min,max) = (max,min)
          }
          let firstIndex = self.startIndex;
          let startPath = self.index(firstIndex, offsetBy:min)
          let endPath = self.index(firstIndex, offsetBy:max)
          let range = startPath ... endPath
          self.removeSubrange(range)
      }
      /// n...m: 刪除此范圍的字符串
      ///
      /// - Parameter closeRange: n...m
      mutating func removeRange(_ closeRange:ClosedRange<Int>) {
          self.remove(from: closeRange.lowerBound, to: closeRange.upperBound)
      }
      /// n..<m: 刪除此范圍的字符串
      ///
      /// - Parameter closeRange: n..<m
      mutating func removeRange(_ subRange:Range<Int>) {
          self.remove(from: subRange.lowerBound, to: subRange.upperBound-1)
      }
    
  • 使用示例

      var example = "ABCDEFG"
    
      example.remove(i: 0)
      print(example) //輸出:BCDEFG
      example.remove(from: 0, to: 1) //刪除全封閉的區(qū)間
      print(example) //輸出:DEFG
      example.removeRange(0...1)
      print(example) //輸出:FG
      example.removeRange(0..<1)
      print(example) //輸出:G
    
如有錯誤 歡迎指正
  • 拋磚引玉,如有更好的請您不吝賜教
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容