gpt4 book ai didi

utf-8 - lua,截断包含utf-8编码字符的字符串

转载 作者:行者123 更新时间:2023-12-02 14:25:54 25 4
gpt4 key购买 nike

我正在重写一个 awk 程序,该程序格式化要输出到状态栏的字符串。我算不上一个程序员,只是一个试图在闲暇时间学习的业余爱好者。

截断任何非 ASCII 字符时,例如西里尔字母 (utf8) 会导致输出损坏,显示为一系列问号。

序曲 Il Ritorno dall'Estero 作品。 89/Mendelsshon/Великие �.../320 kb/s

string.len# 计算字节数,而不是字符数。并且单个西里尔字符被计为 2 个字节而不是 1 个字节。这显然会使截断变得复杂。幸运的是 Lua 5.3 包含 utf8 library , wiki on unicode support简化非 acsii 字符的处理。我修改了“shorten”函数以使用 utf8.len 以获得准确的截断字符数,但问题仍然存在。

--from penlight library, use utf8.len, not string.len
function shorten(s,w)
local ellipsis = "…"
local n_ellipsis = utf8.len(ellipsis)
assert_string(1,s)
if utf8.len(s) > w then
return s:sub(1,w-n_ellipsis) .. ellipsis
end
return s
end

通过进一步阅读,我了解到只要需要截断,就应该使用 utf8.offset。

You should use these functions anywhere you need to manipulate text that you didn’t write yourself or may contain non-ASCII or non-English characters. If you truncate a string at a byte index that is not between whole codepoints you will end up with an invalid UTF-8 string that may render incorrectly or cannot be stored in a DataStore.

If you are truncating a string at an index you should use string.sub with a byte index given by utf8.offset.

我一直在尝试找出如何使用utf8.offset来获取所需的字节索引,但到目前为止成功率为零。如果进一步的上下文有帮助,这是我的 wip full script

任何提示、代码、批评等都将不胜感激。

最佳答案

感谢Egor的解决方案。在 Lua 5.3 中:

return s:sub(1, utf8.offset(s, w - n_ellipsis + 1) - 1) .. ellipsis

关于utf-8 - lua,截断包含utf-8编码字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57858544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com