判断字符串(UTF-8编码)是否为中文、韩文、日文的LUA实现

该博客介绍了如何使用LUA将字符串拆分为单个字符,并通过判断字符的Unicode编码范围来识别是否属于中文、韩文或日文。主要涉及UTF-8编码原理,包括不同字符的字节数识别和CJK编码的判断方法。
首先把字符串拆分成单个字符
-- 拆分出单个字符
function stringToChars(str)
    -- 主要用了Unicode(UTF-8)编码的原理分隔字符串
    -- 简单来说就是每个字符的第一位定义了该字符占据了多少字节
    -- UTF-8的编码:它是一种变长的编码方式
    -- 对于单字节的符号,字节的第一位设为0,后面7位为这个符号的unicode码。因此对于英语字母,UTF-8编码和ASCII码是相同的。
    -- 对于n字节的符号(n>1),第一个字节的前n位都设为1,第n+1位设为0,后面字节的前两位一律设为10。
    -- 剩下的没有提及的二进制位,全部为这个符号的unicode码。
    local list = {}
    local len = string.len(str)
    local i = 1
    while i <= len do
        local c = string.byte(str, i)
        local shift = 1
        if c > 0 and c <= 127 then
            shift = 1
        elseif (c >= 192 and c <= 223) then
            shift = 2
        elseif (c >= 224 and c <= 239) then
            shift = 3
        elseif (c >= 240 and c <= 247) then
            shift = 4
        end
        local char = string.sub(str, i, i+shift-1)
        i = i + shift
        table.insert(list, char)
    end
    return list, len
end
判断CJK编码
function isCJKCode(char)
    local len = string.len(char)
    local chInt = 0
    for i = 1, len do
        local n = string.byte(char, i)
        chInt = chInt * 256 + n
    end
    -- (0x2E80 -- 0x2FDF) -- CJK Radicals Supplement & Kangxi Radicals
    -- (0x2FF0 -- 0x30FF) -- Ideographic Description Characters, CJK Symbols and Punctuation & Japanese
    -- (0x3100 -- 0x31BF) -- Korean
    -- (0x31C0 -- 0x4DFF) -- Other extensions
    -- (0x4E00 -- 0x9FBF) -- CJK Unified Ideographs
    -- (0xAC00 -- 0xD7AF) -- Hangul Syllables
    -- (0xF900 -- 0xFAFF) -- CJK Compatibility Ideographs
    -- (0xFE30 -- 0xFE4F) -- CJK Compatibility Forms
    return (chInt >= 14858880 and chInt <= 14860191)
        or (chInt >= 14860208 and chInt <= 14910399)
        or (chInt >= 14910592 and chInt <= 14911167)
        or (chInt >= 14911360 and chInt <= 14989247)
        or (chInt >= 14989440 and chInt <= 15318719)
        or (chInt >= 15380608 and chInt <= 15572655)
        or (chInt >= 15705216 and chInt <= 15707071)
        or (chInt >= 15710384 and chInt <= 15710607)
end
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值