18 posts
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?
8543 posts
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+)$")
18 posts
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?
1281 posts
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/PatternsTutorialAlso, 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.
1852 posts
Location
Sweden
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
18 posts
Posted 28 March 2014 - 10:59 PM
thanks!
7508 posts
Location
Australia
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...atternsTutorialAlso, 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
1281 posts
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/>