utf8.lua 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. --region *.lua
  2. --Date
  3. --此文件由[BabeLua]插件自动生成
  4. local UTF8 = {}
  5. --
  6. -- lua
  7. -- 判断utf8字符byte长度
  8. -- 0xxxxxxx - 1 byte
  9. -- 110yxxxx - 192, 2 byte
  10. -- 1110yyyy - 225, 3 byte
  11. -- 11110zzz - 240, 4 byte
  12. local function chsize(char)
  13. if not char then
  14. print("not char")
  15. return 0
  16. elseif char > 240 then
  17. return 4
  18. elseif char > 225 then
  19. return 3
  20. elseif char > 192 then
  21. return 2
  22. else
  23. return 1
  24. end
  25. end
  26. -- 计算utf8字符串字符数, 各种字符都按一个字符计算
  27. -- 例如utf8len("1你好") => 3
  28. function UTF8:length(str)
  29. local len = 0
  30. local currentIndex = 1
  31. while currentIndex <= #str do
  32. local char = string.byte(str, currentIndex)
  33. currentIndex = currentIndex + chsize(char)
  34. len = len +1
  35. end
  36. return len
  37. end
  38. -- 截取utf8 字符串
  39. -- str: 要截取的字符串
  40. -- startChar: 开始字符下标,从1开始
  41. -- numChars: 要截取的字符长度
  42. function UTF8:sub(str, startChar, numChars)
  43. local startIndex = 1
  44. while startChar > 1 do
  45. local char = string.byte(str, startIndex)
  46. startIndex = startIndex + chsize(char)
  47. startChar = startChar - 1
  48. end
  49. local currentIndex = startIndex
  50. while numChars > 0 and currentIndex <= #str do
  51. local char = string.byte(str, currentIndex)
  52. currentIndex = currentIndex + chsize(char)
  53. numChars = numChars -1
  54. end
  55. return str:sub(startIndex, currentIndex - 1)
  56. end
  57. --截取utf字符串 用于显示 中文算两个字符 英文算一个 例: 输入 哈哈 哈hh hhhh
  58. -- 2 哈 哈 hh 3:哈 哈h hhh 4: 哈哈 哈hh hhhh
  59. function UTF8:show_sub(str, startChar, numChars)
  60. local startIndex = 1
  61. while startChar > 1 do
  62. local char = string.byte(str, startIndex)
  63. startIndex = startIndex + chsize(char)
  64. startChar = startChar - 1
  65. end
  66. local currentIndex = startIndex
  67. while numChars > 0 and currentIndex <= #str do
  68. local char = string.byte(str, currentIndex)
  69. local len = chsize(char)
  70. if numChars >= 2 then
  71. if len > 1 then
  72. numChars = numChars - 2
  73. else
  74. numChars = numChars - 1
  75. end
  76. currentIndex = currentIndex + len
  77. elseif numChars == 1 then
  78. if len > 1 then
  79. numChars = numChars - 2
  80. else
  81. numChars = numChars - 1
  82. currentIndex = currentIndex + len
  83. end
  84. end
  85. end
  86. return str:sub(startIndex, currentIndex - 1)
  87. end
  88. return UTF8
  89. --endregion