Created
March 24, 2016 09:57
-
-
Save moogoo78/d55c91376228659f3207 to your computer and use it in GitHub Desktop.
lua truncate multi-byte string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local function truncate(s, n, tail) | |
local c = 0 -- 判斷字寬, 中文: 2, 西歐字母: 1 | |
local c2 = 0 -- 判斷字元 (中文大部分3byte, TODO) | |
local add_tail = false | |
local r = "" | |
for i in s:gmatch("[\1-\127\194-\244][\128-\191]*") do | |
if c > n then | |
add_tail = true | |
break | |
end | |
if string.byte(i) > 127 then | |
c = c + 2 | |
c2 = c2 + 3 | |
else | |
c = c + 1 | |
c2 = c2 + 1 | |
end | |
end | |
r = string.sub(s, 0, c2) | |
if add_tail then | |
if tail == nil then | |
r = r .. "..." | |
else | |
r = r .. tail | |
end | |
end | |
return r | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment