---
title: "Twitter的中文字符长度的计算"
url: "https://versun.me/calculating-chinese-character-length-for-twitter"
markdown_url: "https://versun.me/calculating-chinese-character-length-for-twitter.md"
format: "note"
published: "2025-02-18T16:51:09.000Z"
updated: "2026-01-05T05:32:06.000Z"
collections:
  - "Blog"
site: "Versun"
---

# Twitter的中文字符长度的计算

我的 [CMS](https://github.com/versun/versunCMS/) 在博客交叉发布到 X 上时，如果内容较多老是会因为字数限制的原因而发布失败。  
研究了下发现 X 对非英文字符的计算和其它平台不一样，在Mastodon和Bluesky上，一个中文字符均算做一个字符数，但 X 却算做 2 个字符数。

![tweet-2084119437922501002-d14b5d04.jpg](https://media.jant.me/media/sit_01krgk4fnyf24sfk8an30re4xv/files/med_01m94p603tejst5rzfvgfqc169.jpg)![tweet-2084119749295013904-42da0dae.jpg](https://media.jant.me/media/sit_01krgk4fnyf24sfk8an30re4xv/files/med_01m94p61z4ewm9x4ec235qcwza.jpg)![tweet-2084100707423289643-d80c05ce.jpg](https://media.jant.me/media/sit_01krgk4fnyf24sfk8an30re4xv/files/med_01m94p640meswbmacdq5d7ayqc.jpg)

所以，我添加了下面2个函数，一律将非ASCII的字符算做2个字符数，虽然代码不怎么好看，但能用

&lt;pre&gt;def count\_chars(&lt;em&gt;str&lt;/em&gt;)
  &lt;em&gt;str&lt;/em&gt;.each\_char.map { |&lt;em&gt;c&lt;/em&gt;| &lt;em&gt;c&lt;/em&gt;.ascii\_only? ? 1 : 2 }.sum
end
&amp;#10;
def truncate\_twitter\_text(&lt;em&gt;str&lt;/em&gt;, &lt;em&gt;max\_length&lt;/em&gt;)
  &lt;em&gt;current\_length &lt;/em&gt;= 0
  &lt;em&gt;chars &lt;/em&gt;= \[\]
&amp;#10;
  &lt;em&gt;str&lt;/em&gt;.each\_char do |&lt;em&gt;c&lt;/em&gt;|
    &lt;em&gt;char\_length &lt;/em&gt;= &lt;em&gt;c&lt;/em&gt;.ascii\_only? ? 1 : 2
    break if &lt;em&gt;current\_length &lt;/em&gt;+ &lt;em&gt;char\_length &lt;/em&gt;&amp;gt; &lt;em&gt;max\_length
    current\_length &lt;/em&gt;+= &lt;em&gt;char\_length
    chars &lt;/em&gt;&amp;lt;&amp;lt; &lt;em&gt;c
  &lt;/em&gt;end
&amp;#10;
  &lt;em&gt;chars&lt;/em&gt;.join(&amp;#34;&amp;#34;)
end&lt;/pre&gt;
