Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can I split a string into an array of individual characters?

Asked by
Hypgnosis 186
5 years ago

For example, "String 1" would become {'S', 't', 'r', 'i', 'n', 'g', ' ', '1'}

I'm not really sure where to start with this. Any help is appreciated.

1 answer

Log in to vote
1
Answered by 5 years ago
Edited 5 years ago

Remember that you can iterate over strings in several ways. Most often, people use the gmatch iterator because it can identify certain string patterns within a string and return only what is consistent with a given pattern. For example, the programmer can say "give me only the numbers within this string" and the gmatch iterator will do so. The pattern to describe this would be %d+.

In your case, you're not interested in a specific pattern. You just want all the individual characters. You can still achieve this with using gmatch because there is a special character that matches any character. It is simply just a dot (.)

Example:

local str = "Hello World"

-- array of characters in 'str'
local chars = {}

-- using gmatch as the iterator of the for loop, match every character using the '.' symbol as the pattern.
for c in string.gmatch(str, ".") do
    chars[#chars+1] = c
end

And so, chars would now refer to the array {"H", "e"," l", "l", "o", " ", "W", "o", "r", "l", "d"} I hope this helps and answers your question. If you have any further questions, just let me know.

0
Works perfectly with a great explanation! Thanks. Hypgnosis 186 — 5y
Ad

Answer this question