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

Spliting Strings at certain characters!

Started by Wing, 06 January 2013 - 07:55 AM
Wing #1
Posted 06 January 2013 - 08:55 AM
Hi just wondering if there is an easy way of splitting strings in sections after a comma or something.
Ex:
  a =  "Hello my friends, how are you today?"
  b = split(a,2)   --Puts the string's sections into a table and returns the position in the table
  print( b )

Output:
how are you today?

Catching my drift?
Exerro #2
Posted 06 January 2013 - 09:27 AM

function sky.util.split(str,pat)
local t = {}
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
  if s ~= 1 or cap ~= "" then
table.insert(t,cap)
  end
  last_end = e+1
  s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
  cap = str:sub(last_end)
  table.insert(t, cap)
end
return t
end
a function someone helped me make (aka completely did himself and generously gave to me :P/>)
returns a table of what it split the stuff into
i.e. sky.util.split("Hello, how are you",",")
would return equivalent of {"Hello"," how are you"}
Wing #3
Posted 06 January 2013 - 09:37 AM
Thanks man!
Exerro #4
Posted 06 January 2013 - 09:39 AM
if you just remove sky.util from the front it will work fine
btw you can also use this to split it into characters using split(string,"[nothing]")
and you can do things like this :
split("line1-:-line2-:-line3-:-line4","-:-") which is useful for sending an infinite amount of lines in one string via rednet or something

email receiver:
message = "title-:::-line1-:-line2-:-line3-:-line4-:-line5"
subject = split(message,"-:::-")[1]
body = split(split(message,"-:::-")[2],"-:-")
ChunLing #5
Posted 06 January 2013 - 10:38 AM
Hmmm…most people would just use string.gmatch().

Also, you can send strings including line returns through rednet already.

I can imagine other uses for this function, but I'd probably still rather use gmatch.
remiX #6
Posted 06 January 2013 - 11:21 AM
Someone made a thread about this in october and I've had it bookmarked ever since.


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

This code is shorter than the previous and easier to understand, imo.

ps: try using the search function ;)/>

edit: misread op (._.) but this is still a good function