7 kyu: Count of codepoints in a UTF-8 string
題目是算UTF-8字串的長度,
這題我實在不知道啥好方法,
可能也不太了解題目,
但是想到這種格式轉換,
在實際應用上,都是直接查答案的,
因此就直接問AI了,
AI的解法如下:
local function count_codepoints(s)
local count = 0
for i = 1, #s do
local b = s:byte(i)
-- b < 128: ASCII
-- b >= 192: UTF-8 leading byte
if b < 128 or b >= 192 then
count = count + 1
end
end
return count
end
return count_codepoints不過這題AI最先的解法,
其實很多餘,
在 Lua 5.3+ 或 Lua 5.4 裡,其實已經內建,
採用以下的解法就好:
return utf8.len
沒有留言:
張貼留言