Created
February 23, 2016 07:28
-
-
Save litefeel/7eac2d9a81a282c01ae8 to your computer and use it in GitHub Desktop.
utf8len utf8sub
This file contains hidden or 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
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