剛遇到一個坑,lua裏 string.len() 中文長度算3(不排除某些漢字可能佔4的可能)不過計算長度最好還是用 #,少用string.len()
搞了兩小時,終於讓我找到一個很好的解決辦法。
local _,count = string.gsub(text, "[^\128-\193]", "")
匹配128到193以外的字節,然後替換成空字符串。長度直接 count就行。
這樣不管是英文還是中文,都算一個長度。
既然標題上是多種,肯定會有另外一種。假設我這個長度只是用做顯示呢,中文算2個字符,英文算1個字符呢。
local count = 0
for uchar in string.gfind(text, "([%z\1-\127\194-\244][\128-\191]*)") do
if #uchar ~= 1 then
count = count +2
else
count = count +1
end
end
這樣就可以啦,我真佩服我自己的機智