This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
jay5476's profile picture

How To Split A String Into Its Individual Letters

Started by jay5476, 23 July 2013 - 03:30 AM
jay5476 #1
Posted 23 July 2013 - 05:30 AM
I have always wanted to know how to do this, if it is possible please tell me with an explanation on how it works
albrat #2
Posted 23 July 2013 - 05:48 AM
I had troubles understanding it at first then once I got the hang of string.* () (from the lua handbook) I couldn't understand why I had so much trouble with it. :D/>

text = "this string is for splitting" -- our text
for a = 1, string.len(text)+1 do  -- for 1 to the number of letters in our text + 1
print (string.sub(text, a,a)) -- split the string with the start and end at "a"
end  -- repeat untill the for loop ends

The above code will simply print each character to the screen.
instead of print(…) you could use a table and insert each character into a table, eg. tabletxt = string.sub(text,a,a)


edit :: oopsy, I did not miss a , while typing too fast. ( looks around and checks if anyone is looking and corrects the typo. ) ** stealths away into the sunshine **
Edited on 23 July 2013 - 05:04 AM
LBPHacker #3
Posted 23 July 2013 - 06:25 AM
Overkill time!… (That means: Yes, I know the question's been answered already, but I feel like posting an answer anyways.)
You could use Lua patterns for this as well:
local str = "something"
local result = {}
for letter in str:gmatch(".") do table.insert(result, letter) end

By the way:

text = "this string is for splitting" -- our text
for a = 1, string.len(text)+1 do  -- for 1 to the number of letters in our text + 1
print (string.sub(text a,a)) -- split the string with the start and end at "a"
end  -- repeat untill the for loop ends
You miss a comma on the third line after "text".
EDIT: AND string.len(text) + 1 is totally nothing, since it's the n+1st character of an n-long string. Use "#text"
albrat #4
Posted 23 July 2013 - 07:06 AM
I origionally typed it as #text but second guessed myself and changed it. lol (moments insanity) (extended version)
KaoS #5
Posted 23 July 2013 - 08:45 AM
Overkill time!… (That means: Yes, I know the question's been answered already, but I feel like posting an answer anyways.)
You could use Lua patterns for this as well:
local str = "something"
local result = {}
for letter in str:gmatch(".") do table.insert(result, letter) end

even easier

local function split(str)
  if #str>0 then return str:sub(1,1),split(str:sub(2)) end
end

you don't have to define a table but you can just

local results={split("randomstring!!")}
if you want a table and

local res1,res2,res3=split("hai")
if you want individual vars