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

Split strings into an array.

Started by Jasonfran, 21 October 2012 - 10:05 AM
Jasonfran #1
Posted 21 October 2012 - 12:05 PM
I need a way to split strings into an array similar to how you can in java.

Java is like this:


String text = "a line of text";
String splits[] = text.split(" ");

System.out.println(splits[1] + " " + splits[4]);

Result:

A text

I'm not a noob but I'm not a pro so I would like an explanation along with it, but it's not necessary as I am quite good at figuring things out.
ChunLing #2
Posted 21 October 2012 - 12:16 PM
You use the string functions. In this case, I think that you use something like:
local _,_,begin,endr = text:find("^(%a+)(%a+)$")
This should "capture" the first letter sequence and last letter sequence. Check here for more information on string.find…um, and the above can be written as:
local _,_,begin,endr = string.find(text,"^(%a+)(%a+)$")

Ugh, I fail at reading. No, the string functions of lua are somewhat limited compared to java. It can be done, but not super easily.
Edited on 21 October 2012 - 10:19 AM
sjele #3
Posted 21 October 2012 - 12:26 PM

yourString = "This is a string with words" --In here we define our string
line = {} --Define a empty table for our words
for word in string.gmatch(yourString, "%w+")  --We go thru the string word by word ("%w+") and give one word at a time the value word
table.insert(line, word) --WE take our word and put it in the table line.
end --end our for loop

print(line[1].." "..line[3]) –would output This a
Jasonfran #4
Posted 21 October 2012 - 12:50 PM
Thanks!