Help us understand the problem. What is going on with this article?

標準ライブラリの utf8 を使う

More than 5 years have passed since last update.

Lua 5.3 で utf8 が標準ライブラリとして導入されたので、練習。

まずはコードポイントから文字列を生成してみよう。次のコードは「あいうえお」を表示する。

print(utf8.char(0x3042, 0x3044, 0x3046, 0x3048, 0x304A))

逆に文字列からコードポイントを求めてみよう

print(string.format("U+%X", utf8.codepoint("あ")))

文字数を求めてみよう。

str = "あいうえお"
print(utf8.len(str))

for ループで1文字ずつコードポイントと先行バイトの位置を求めてみよう。

str = "あいうえお"

for p, c in utf8.codes(str) do
    print(string.format("%d U+%X", p, c))
end

1文字ずつターミナルに表示しては改行してみよう。コードポイントを文字に変換すればよい。

str = "あいうえお"

for p, c in utf8.codes(str) do
    print(string.format("%s", utf8.char(c)))
end

先行バイトの位置を求めて、スライスすることで、1文字ずつ表示させることもできる。

str = "あいうえお"
length = utf8.len(str)

for i = 1, length do
  lead = utf8.offset(str, i)
  trail = utf8.offset(str, i+1) - 1
  print(string.sub(str, lead, trail))
end
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした