Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

✓ Accepted answer

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.

1 comment

0

Works perfectly with a great explanation! Thanks.

This discussion is preserved as it was. New answers, comments, and votes are closed.