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

Cut last word

Started by Ch1ck3nL1v3r, 28 March 2014 - 05:29 PM
Ch1ck3nL1v3r #1
Posted 28 March 2014 - 06:29 PM
I would like to create a system to cut the last word off a string. So "This is an example" would become "this is an" and "example"

any ideas for how I could do this?
Lyqyd #2
Posted 28 March 2014 - 06:44 PM
You'd use string.match. Something like this might do it:


first, last = string.match(str, "(.-)%s(%S+)$")
Ch1ck3nL1v3r #3
Posted 28 March 2014 - 07:38 PM
Yeah that works, thanks!

Do you know how I could check if a string contains a space, so I can avoid the error when it tries to find the space in a string without one?
CometWolf #4
Posted 28 March 2014 - 08:17 PM
It's pretty much the same thing, that "%s" that Lyqyd uses for his pattern there represents a space.
http://lua-users.org/wiki/PatternsTutorial
Also, the correct code for your first question would be

first, rest = string.match(str, "^(.-)%s(.+)$")
Otherwise you'd only get the second to last and last words.
TheOddByte #5
Posted 28 March 2014 - 08:17 PM
Is it something like this you meant?

local text = "Hello World!"
if text:find( " " ) then
	print("This string has a space!")
else
	print( "It doesn't have a space")
end
Edited on 28 March 2014 - 07:18 PM
Ch1ck3nL1v3r #6
Posted 28 March 2014 - 10:59 PM
thanks!
theoriginalbit #7
Posted 28 March 2014 - 11:47 PM
It's pretty much the same thing, that "%s" that Lyqyd uses for his pattern there represents a space.
http://lua-users.org...atternsTutorial
Also, the correct code for your first question would be

first, rest = string.match(str, "^(.-)%s(.+)$")
Otherwise you'd only get the second to last and last words.
Well a better pattern for checking if a string contains a space — other than just using string.find which doesn't need a pattern, like hellkid did — would be to do this

local function containsSpace(str)
  return str:match("%s") ~= nil
end
CometWolf #8
Posted 29 March 2014 - 12:22 AM
i dunno why you quoted me for that, i didn't post any solution to the second question :P/>