How to find the last word in string?

Hi.

How would I go about finding the last word in a string?

Say we have a string “roses are red”. I’d like the function to return “red”.

I was thinking I should determine position of the last space and go from there. Is that the right track?

  • Reverse search the string for the last space

  • Then extract all letters after that.

    local tmp = “roses are red” local lastSpace = string.find( string.reverse(tmp), '% ’ ) - 1 print( tmp:sub(-lastSpace) )

Tip: A Lua expert probably has a more efficient way to do this, but this works fine too.

Oh, I forgot to say.  If you’re an SSK user, this is the way I would do it:

local tmp = "roses are red" local last = string.split( tmp, "% " ) print( last[#last] )

string.match, fe

s = "roses are red" print(s:match("%s(%S+)$")) -- or use "%s\*(%S+)$" if a space is not guaranteed

Thank you all. I’ll use @davebollinger 's approach because it seems the most elegant &, come to think of it, the space is not guaranteed.

EDIT

Actually, @davebollinger, would you care to explain a bit the logic behind this pattern? 

I know %s is for space and the * is the wildcard but what does (%S+)$ do?

  • Reverse search the string for the last space

  • Then extract all letters after that.

    local tmp = “roses are red” local lastSpace = string.find( string.reverse(tmp), '% ’ ) - 1 print( tmp:sub(-lastSpace) )

Tip: A Lua expert probably has a more efficient way to do this, but this works fine too.

Oh, I forgot to say.  If you’re an SSK user, this is the way I would do it:

local tmp = "roses are red" local last = string.split( tmp, "% " ) print( last[#last] )

string.match, fe

s = "roses are red" print(s:match("%s(%S+)$")) -- or use "%s\*(%S+)$" if a space is not guaranteed

Thank you all. I’ll use @davebollinger 's approach because it seems the most elegant &, come to think of it, the space is not guaranteed.

EDIT

Actually, @davebollinger, would you care to explain a bit the logic behind this pattern? 

I know %s is for space and the * is the wildcard but what does (%S+)$ do?