2

I have a function to put the first letter of a string into uppercase.

function firstToUpper(str)
   return string.gsub(" "..str, "%W%l", string.upper):sub(2)
end

Now I need a function to add a space between small and big letters in a string like:

HelloWorld ----> Hello World

Do you know any solution for Lua?

Piglet
  • 27,501
  • 3
  • 20
  • 43
Karto1695
  • 21
  • 1

2 Answers2

4

str:gsub("(%l)(%u)", "%1 %2") returns a string that comes with a space between any lower upper letter pair in str.

Please read https://www.lua.org/manual/5.4/manual.html#pdf-string.gsub

Piglet
  • 27,501
  • 3
  • 20
  • 43
0
local function spaceOut(str)
     local new = str
     repeat
         local start,finish = new:find("%l%u")
         new = new:gsub("%l%u",new:sub(start,start).." "..new:sub(finish,finish),1)
     until new:find("%l%u") == nil
     return new
 end

 print(spaceOut("ThisIsMyMethodForSpacingWordsOut"))
  • 2
    all you do here is already supported by string.gsub. there is no need to use string.find and a loop. `new` is also superfluous. why not name your parameter `new` or use `str`? – Piglet May 30 '21 at 14:53
  • Before I wrote this script, I thought you couldn't change the value of a parameter in a function. Thanks for letting me know about this easier method – luckysenpai May 31 '21 at 16:49