萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Lua UTF-8 字串長度計算與截斷省略號:完整函式庫

痛點:Lua 5.1/5.2 無原生 UTF-8 支援

#str 回傳**位元組數**,非字元數。中文 UTF-8 佔 3 位元組,直接用 # 會誤判長度。

函式一:精確計算 UTF-8 字元數

local function utf8_len(str)
    local len = #str
    local left = len
    local cnt = 0
    local first_byte = {0, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC}  -- UTF-8 首位元組門檻
    
    while left > 0 do
        local byte = string.byte(str, -left)  -- 從左往右掃描
        local i = #first_byte
        while first_byte[i] do
            if byte >= first_byte[i] then
                left = left - i
                break
            end
            i = i - 1
        end
        cnt = cnt + 1
    end
    return cnt
end

-- 測試
print(utf8_len("Hello"))      -- 5
print(utf8_len("你好"))        -- 2
print(utf8_len("Hello世界"))   -- 7

函式二:截斷並加省略號(支援中英混排寬度)

-- 參數:字串、最大顯示寬度(中文算 2)、顯示寬度(預設 max-3)
function utf8_truncate(s, max_w, show_w)
    if not s or not max_w then return s end
    show_w = show_w or max_w - 3
    
    local bytes = {string.byte(s, 1, #s)}
    local chars, widths = {}, {}
    local i, w = 1, 0
    
    while i <= #bytes do
        local b = bytes[i]
        local char_len = (b < 0x80) and 1
                       or (b < 0xE0) and 2
                       or (b < 0xF0) and 3
                       or 4
        local ch = string.sub(s, i, i + char_len - 1)
        local char_w = (char_len == 1) and 1 or 2  -- 中日韓算 2 寬度
        table.insert(chars, ch)
        table.insert(widths, char_w)
        w = w + char_w
        i = i + char_len
    end
    
    if w <= max_w then return s end  -- 無需截斷
    
    local out, cur = {}, 0
    for idx, ch in ipairs(chars) do
        cur = cur + widths[idx]
        if cur > show_w then break end
        table.insert(out, ch)
    end
    return table.concat(out) .. "..."
end

-- 測試
print(utf8_truncate("Hello世界", 10))      -- "Hello世..."
print(utf8_truncate("你好世界", 6))        -- "你好..."
print(utf8_truncate("Hello", 10))          -- "Hello" (未超寬)

Lua 5.3+ / LuaJIT 2.1+ 現代寫法

-- 內建 utf8 库 (Lua 5.3+)
local function utf8_len_modern(s)
    return utf8.len(s) or 0  -- 非法序列回傳 nil
end

local function utf8_truncate_modern(s, max_w, show_w)
    -- 同邏輯,改用 utf8.codes(s) 迭代器
    -- 略
end

結語

UTF-8 多位元組特性導致位元組長度 ≠ 字元數。掌握首位元組判斷邏輯(0x00-0x7F 1 字節、0xC0-0xDF 2 字節、0xE0-0xEF 3 字節、0xF0-0xF7 4 字節),即可手寫高效 UTF-8 處理函式。專案若能用 Lua 5.3+,請直接使用內建 utf8 库。

copyright © 萬盛學電腦網 all rights reserved