Swift 获取字符串长度的理解(2018-01-10)

Swift 获取字符串长度

  • 字符串的长度获取,可以从以下几种情况理解
    • 字符长度(语义理解的长度)
    • 不同字符编码的长度
      • 字符串unicode长度
      • 字符串utf16长度
      • 字符串utf32长度(和unicode相等)
      • 字符串UTF-8长度
  • 语义字符长度

      let cafe = "Cafe\u{301} du 🌍"  
      print(cafe)
      // Prints "Café du 🌍"  
      print(cafe.count)
      // Prints "9"
      print(Array(cafe))
      // Prints "["C", "a", "f", "é", " ", "d", "u", " ", "🌍"]"
    
    • 不同字符编码的长度
      - unicode字符长度

              print(cafe.utf16.count)
              // Prints "11"
              print(Array(cafe.utf16))
              // Prints "[67, 97, 102, 101, 769, 32, 100, 117, 32, 55356, 57101]"
      - utf16字符长度
      
              let nscafe = cafe as NSString
              print(nscafe.length)
              // Prints "11"
              print(nscafe.character(at: 3))
              // Prints "101"
      - UTF-8字符长度
      
              print(cafe.utf8.count)
              // Prints "14"
              print(Array(cafe.utf8))
              // Prints "[67, 97, 102, 101, 204, 129, 32, 100, 117, 32, 240, 159, 140, 141]"
      
  • How to measuring the Length of a String

    • sample1:

        let capitalA = "A"
        print(capitalA.count)
        // Prints "1"
        print(capitalA.unicodeScalars.count)
        // Prints "1"
        print(capitalA.utf16.count)
        // Prints "1"
        print(capitalA.utf8.count)
        // Prints "1"
      
    • sample2:

        let flag = "🇵🇷"
        print(flag.count)
        // Prints "1"
        print(flag.unicodeScalars.count)
        // Prints "2"
        print(flag.utf16.count)
        // Prints "4"
        print(flag.utf8.count)
        // Prints "8"
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 字符串和字符 甲串是一系列字符,如的"hello, world"或"albatross"。Swift字符串由Str...
    Fuuqiu阅读 1,050评论 0 0
  • 特性: 1. Unicode 编码规范: 可以使用任何字符,表情 2. 与本地语言无关:无需去考虑汉子及其他字体乱...
    a7a5046b89c8阅读 464评论 0 0
  • 1 .字符串字面量 String 在Swift中字符串字面量是由双引号" " 包裹着的 像我们在 Swift 3 ...
    iceMaple阅读 1,158评论 1 2
  • 夕阳缓缓地落下,涂上了金黄色的大海。 沙滩上的行人越来越多,两排两排的脚印刻在了地面上,看不清是哪一对情侣的脚印,...
    西红柿炒蛋加糖阅读 335评论 0 0
  • 此时相望不相闻,愿逐月华流照君。 临近月圆之夜,满脑海的都是这句诗,无声地在耳畔一遍又一遍的回旋。就像往常耳麦里的...
    捉影捕风阅读 324评论 0 2