加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Lua – 从文件中读取一个UTF-8字符

发布时间:2020-12-14 21:49:57 所属栏目:大数据 来源:网络整理
导读:是否可以从文件中读取一个UTF-8字符? file:read(1)返回奇怪的字符,当我打印它时. function firstLetter(str) return str:match("[%z1-127194-244][128-191]*")end 函数从字符串str返回一个UTF-8字符.我需要以这种方式读取一个UTF-8字符,但是从输入文
是否可以从文件中读取一个UTF-8字符?

file:read(1)返回奇怪的字符,当我打印它时.

function firstLetter(str)
  return str:match("[%z1-127194-244][128-191]*")
end

函数从字符串str返回一个UTF-8字符.我需要以这种方式读取一个UTF-8字符,但是从输入文件(不想将某些文件读取到内存中 – 通过文件:read(“* all”))

问题非常类似于这篇文章:
Extract the first letter of a UTF-8 string with Lua

解决方法

function read_utf8_char(file)
  local c1 = file:read(1)
  local ctr,c = -1,math.max(c1:byte(),128)
  repeat
    ctr = ctr + 1
    c = (c - 128)*2
  until c < 128
  return c1..file:read(ctr)
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读