Search code examples
lualove2d

How can I put string in other string by position


My string is 'Hllo'. I want to put inside it 'e' after the 'H' by its position, this case, position number 2.


Solution

  • You can simply cut contents until position you want to place your character on, then add the character and finally concat the characters on and after position.

    src = "Hllo"
    result = string.sub(src, 1, string.find(src, "H")) .. "e" .. string.sub(src, string.find(src, "H")+1)
    

    The first part of code gets position of 'H' andf cuts the start (in this case 'H' only). Second part adds character you want to insert. Third part adds every character after 'H' in source string to result.