Skip to content

Instantly share code, notes, and snippets.

@litefeel
Created February 23, 2016 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save litefeel/7eac2d9a81a282c01ae8 to your computer and use it in GitHub Desktop.
Save litefeel/7eac2d9a81a282c01ae8 to your computer and use it in GitHub Desktop.
utf8len utf8sub
function string.utf8len(s)
if s == nil or s == "" then return 0 end
local n = 0
for i = 1, #s do
local c = string.byte(s, i)
if c < 0x80 or c >= 0xC0 then
n = n + 1
end
end
return n
end
function string.utf8sub(s, i, j)
if s == nil or s == "" then return s end
if not j then j = #s end
local bi, ei = nil, nil
local n = 0
for ii = 1, #s do
local c = string.byte(s, ii)
if c < 0x80 or c >= 0xC0 then
n = n + 1
end
if n == i and not bi then bi = ii end
if n == j + 1 and not ei then ei = ii - 1 end
end
if not ei then ei = #s end
return string.sub(s, bi, ei)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment