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

获取Twitter字符数

  •  2
  • Nayef  · 技术社区  · 6 年前

    我有一个程序,它是一个Twitter tweets的编辑器,它的计算文本,使其小于280个字符作为Twitter限制。

    我使用utf8属性如下:

    var str = "℞"
    let r = str.utf8.count
    

    结果=3

    我怎样才能得到正确的计数:2

    1 回复  |  直到 6 年前
        1
  •  2
  •   OOPer    6 年前

    Counting characters

    Tweet长度是通过NFC中的码点数来度量的 文本的规范化版本。

    precomposedStringWithCanonicalMapping unicodeScalars.count .

    所以,Swift中正确的代码应该是这样的:

    var str = "℞"
    let r = str.precomposedStringWithCanonicalMapping.unicodeScalars.count
    print(r) //->1
    

    2 对于 ℞ .


    (感谢Rakesha Shastri) 我相信上面的代码正确地实现了我在上面链接的文档中描述的规范。


    text Tweet parsing library ,但它显示的结果与我的代码相同。

    let len = TwitterText.tweetLength(str)
    print(len) //->1
    

    TwitterText.tweetLength(_:) 更复杂,因为它处理 t.co links . 因此,当某些URL包含在文本中时,它会生成与我的代码不同的输出。)


    更新 )

    我不确定所提到的twitter应用程序是否是开源的,但我猜它们显示了 加权长度 文本Tweet解析库

    let config = TwitterTextConfiguration(fromJSONResource: kTwitterTextParserConfigurationV2)
    let parser = TwitterTextParser(configuration: config)
    let result = parser.parseTweet(str)
    print(result.weightedLength) //->2