Search code examples
iosswiftstringxcodetwitter

Getting Twitter characters count


I have a program, it is an editor for Twitter tweets, it's counting the text to make it less than 280 character as twitter restriction.

I use for that utf8 property like this:

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

The result = 3

This symbol (℞) and more like it takes only 2 character in twitter counter but the result in this code gave me 3, so i can't give the user the exact character count!

How can I get the correct count: 2


Solution

  • Counting characters

    Tweet length is measured by the number of codepoints in the NFC normalized version of the text.

    In Swift, you can get the NFC normalized form through precomposedStringWithCanonicalMapping, and the number of codepoints by unicodeScalars.count.

    So, the right code in Swift should be like this:

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

    The code above shows consistent result with some character counters on the web, I do not understand why you get 2 for .


    (Thanks to Rakesha Shastri.) I believe the code above correctly implements the specification described in the documentation I linked above.

    But it is reported that the actual Twitter does not work exactly as in the doc. (Sorry, I do not tweet myself.) We may need to guess or find another reliable source to make it fit for the actual Twitter.


    I tried the official library text Tweet parsing library, but it shows the same result as my code.

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

    (Though, the code of TwitterText.tweetLength(_:) is far more complex, as it handles t.co links. So, when some URLs are included in the text, it generates different output than my code.)


    (UPDATE)

    I'm not sure as the referred twitter apps are not open-source, but I guess they are showing the weighted length described in the text Tweet parsing library page linked above.

    You may need to write something like this with importing the library using pod.

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