代码之家  ›  专栏  ›  技术社区  ›  Senseful

当与nsstring API交互时,我应该使用哪个swift字符计数?

  •  1
  • Senseful  · 技术社区  · 6 年前

    有时,我需要在后台使用依赖nsstring/nsrange的API,但我的大多数代码都是swift格式的。

    当我需要提供一个索引(或范围)时,我应该使用哪个快速字符计数?

    例如,给定此函数:

    func replace(_ string: String, characterAtIndex characterIndex: Int) -> String {
      let regex = try! NSRegularExpression(pattern: ".", options: [])
      let range = NSRange(location: characterIndex, length: 1)
      let mutableString = NSMutableString(string: string)
      regex.replaceMatches(in: mutableString, options: [], range: range, withTemplate: "!")
      return mutableString as String
    }
    

    我应该使用哪种不同的方法来获取字符串上的字符计数?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Senseful    6 年前

    documentation for NSString.length

    • string.utf16.count (string as NSString).length

    • string.count


    let header = "NSString   .utf16❔   encodedOffset❔   NSRange❔   .count❔   .characters❔   distance❔   .unicodeScalars❔   .utf8❔   Description"
    var format = "     %3d     %3d ❓            %3d ❓      %3d ❓     %3d ❓          %3d ❓       %3d ❓              %3d ❓    %3d ❓   %@"
    format = format.replacingOccurrences(of: "❓", with: "%@") // "❓" acts as a placeholder for "%@" to align the text perfectly
    
    print(header)
    
    test("")
    test("abc")
    test("❌")
    test("🤞🏻")
    test("☾test")
    test("👨‍👩‍👧‍👧")
    test("👨\u{200d}👩\u{200d}👧\u{200d}👦")
    test("👨👩👧👦")
    test("\u{1F468}")
    test("👶🏼👧🏽🧒🏾👦🏻👩🏿🧑🏻👨🏽👱🏽‍♀️👱🏼‍♂️🧔🏾👵🏽🧓🏻👴🏾")
    test("你好吗")
    test("مرحبا", "Arabic word")
    test("م", "Arabic letter")
    test("שלום", "Hebrew word")
    test("ם", "Hebrew letter")
    
    func test(_ s: String, _ description: String? = nil) {
      func icon(for length: Int) -> String {
        return length == (s as NSString).length ? "✅" : "❌"
      }
    
      let description = description ?? "'" + s + "'"
      let string = String(
        format: format,
        (s as NSString).length,
        s.utf16.count, icon(for: s.utf16.count),
        s.endIndex.encodedOffset, icon(for: s.endIndex.encodedOffset),
        NSRange(s.startIndex..<s.endIndex, in: s).upperBound, icon(for: NSRange(s.startIndex..<s.endIndex, in: s).upperBound),
        s.count, icon(for: s.count),
        s.characters.count, icon(for: s.characters.count),
        s.distance(from: s.startIndex, to: s.endIndex), icon(for: s.distance(from: s.startIndex, to: s.endIndex)),
        s.unicodeScalars.count, icon(for: s.unicodeScalars.count),
        s.utf8.count, icon(for: s.utf8.count),
        description)
      print(string)
    }
    

    NSString   .utf16❔   encodedOffset❔   NSRange❔   .count❔   .characters❔   distance❔   .unicodeScalars❔   .utf8❔   Description
           0       0 ✅              0 ✅        0 ✅       0 ✅            0 ✅         0 ✅                0 ✅      0 ✅   ''
           3       3 ✅              3 ✅        3 ✅       3 ✅            3 ✅         3 ✅                3 ✅      3 ✅   'abc'
           1       1 ✅              1 ✅        1 ✅       1 ✅            1 ✅         1 ✅                1 ✅      3 ❌   '❌'
           4       4 ✅              4 ✅        4 ✅       1 ❌            1 ❌         1 ❌                2 ❌      8 ❌   '🤞🏻'
           5       5 ✅              5 ✅        5 ✅       5 ✅            5 ✅         5 ✅                5 ✅      7 ❌   '☾test'
          11      11 ✅             11 ✅       11 ✅       1 ❌            1 ❌         1 ❌                7 ❌     25 ❌   '👨‍👩‍👧‍👧'
          11      11 ✅             11 ✅       11 ✅       1 ❌            1 ❌         1 ❌                7 ❌     25 ❌   '👨‍👩‍👧‍👦'
           8       8 ✅              8 ✅        8 ✅       4 ❌            4 ❌         4 ❌                4 ❌     16 ❌   '👨👩👧👦'
           2       2 ✅              2 ✅        2 ✅       1 ❌            1 ❌         1 ❌                1 ❌      4 ❌   '👨'
          58      58 ✅             58 ✅       58 ✅      13 ❌           13 ❌        13 ❌               32 ❌    122 ❌   '👶🏼👧🏽🧒🏾👦🏻👩🏿🧑🏻👨🏽👱🏽‍♀️👱🏼‍♂️🧔🏾👵🏽🧓🏻👴🏾'
           3       3 ✅              3 ✅        3 ✅       3 ✅            3 ✅         3 ✅                3 ✅      9 ❌   '你好吗'
           5       5 ✅              5 ✅        5 ✅       5 ✅            5 ✅         5 ✅                5 ✅     10 ❌   Arabic word
           1       1 ✅              1 ✅        1 ✅       1 ✅            1 ✅         1 ✅                1 ✅      2 ❌   Arabic letter
           4       4 ✅              4 ✅        4 ✅       4 ✅            4 ✅         4 ✅                4 ✅      8 ❌   Hebrew word
           1       1 ✅              1 ✅        1 ✅       1 ✅            1 ✅         1 ✅                1 ✅      2 ❌   Hebrew letter
    

    • (s as NSString).length s.utf16.count s.endIndex.encodedOffset NSRange(s.startIndex..<s.endIndex, in: s)
    • s.count s.characters.count s.distance(from: s.startIndex, to: s.endIndex)

    public extension String {
    
      var nsrange: NSRange {
        return NSRange(startIndex..<endIndex, in: self)
      }
    }
    

    replace("👨‍👩‍👧‍👧", characterAtIndex: "👨‍👩‍👧‍👧".utf16.count - 1) // 👨‍👩‍👧‍�!