【问题标题】:Get the UTF-8 Encoding of a Character in Bytes以字节为单位获取字符的 UTF-8 编码
【发布时间】:2016-06-27 22:01:26
【问题描述】:

String 上,我可以使用utf8count 来获取使用UTF-8 编码对字符串进行编码所需的字节数:

"a".utf8.count // 1
"チャオ".utf8.count // 9
"チ".utf8.count // 3

但是,我没有在单个 Character 值上看到等效方法。要获得将字符串中的字符编码为 UTF-8 所需的字节数,我可以逐个字符地遍历字符串,将 Character 转换为 String,并获取该字符串的 utf8.count

"チャオ".characters.forEach({print(String($0).utf8.count)}) // 3, 3, 3

这似乎是不必要的冗长。有没有办法在 Swift 中获取 Character 的 UTF-8 编码?

【问题讨论】:

  • 为什么是underestimateCountlet c = "チャオ".utf8.count 给出字符串的确切 UTF-8 长度。
  • @MartinR 好点,我将使用count 代替。但是如何逐个字符地获取大小呢?
  • 据我所知,转换为字符串是唯一的方法。
  • 哦,好的,感谢您的光临。

标签: swift string utf-8 character-encoding character


【解决方案1】:

Character 对其 UTF-8 表示没有直接(公共)访问器。

Character.swift 中有一些内部方法处理 UTF-8 字节,但公共的东西在 String.UTF8ViewStringUTF8.swift.

因此String(myChar).utf8.count是正确的获取方式 UTF-8 表示的字符长度。

【讨论】:

    猜你喜欢
    • 2013-04-26
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2014-06-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    相关资源
    最近更新 更多