乐闻世界logo
搜索文章和话题

How to iterate individual characters in Lua string?

1个答案

1

In Lua, iterating over individual characters in a string can be achieved in multiple ways. I'll demonstrate two common approaches:

Method 1: Using string.sub

We can use the string.sub function within a for loop to extract each character sequentially. The string.sub(s, i, j) function extracts a substring from position i to j in string s. When i and j are set equal, it retrieves each character individually.

lua
local str = "hello" for i = 1, #str do local char = string.sub(str, i, i) print(char) end

In this example, #str is used to obtain the string length, and string.sub(str, i, i) retrieves the character at position i. The loop will sequentially print 'h', 'e', 'l', 'l', 'o'.

Method 2: Using utf8.codes

For Lua 5.3 and newer versions, when handling Unicode strings, the utf8.codes function can be used to correctly process strings containing multi-byte Unicode characters.

lua
local str = "안녕하세요" for p, c in utf8.codes(str) do print(utf8.char(c)) end

Here, utf8.codes(str) is an iterator that traverses each character in the string (including Unicode characters), where p is the character's position and c is its code point. utf8.char(c) converts the code point back to a character. This will print '안', '녕', '하', '세', '요' one by one.

Both methods have their respective use cases: if you're working with ASCII or single-byte character sets, the first method is simple and effective. For handling Unicode text that includes multi-byte characters, the second method is more appropriate.

2024年7月25日 13:50 回复

你的答案