Jump to content




Split strings into an array.


  • You cannot reply to this topic
3 replies to this topic

#1 Jasonfran

  • Members
  • 148 posts
  • LocationEngland

Posted 21 October 2012 - 11:05 AM

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.

#2 ChunLing

  • Members
  • 2,027 posts

Posted 21 October 2012 - 11:16 AM

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 by ChunLing, 21 October 2012 - 11:19 AM.


#3 sjele

  • Members
  • 334 posts
  • LocationSomewhere on the planet called earth

Posted 21 October 2012 - 11:26 AM

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

#4 Jasonfran

  • Members
  • 148 posts
  • LocationEngland

Posted 21 October 2012 - 11:50 AM

Thanks!





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users