Insert character at specified position in string in Lua
Thought analysis
Recently, I encountered a requirement in the client, and I needed to insert a space into the string to display. The general idea is,Split the string into left and right sides from the inserted index position, then add a string to be inserted in the middle, and then combine them together, and then the method considers that the prefix of the string in the project may have identification characters (parameter flag), so it has added a function to add the length of the prefix. Of course, if there is no prefix, the flag can not be passed.
[release code
function string_insert(str,index,insertStr, flag)
if flag and string.find(str, flag) ~=nil then
index = index + #flag
end
local pre = string.sub(str, 1, index -1)
local tail = string.sub(str, index, -1)
local createStr = string.format("%s%s%s", pre, insertStr, tail)
print(createStr)
return createStr
end
print(string_insert('abcdefg',3,' ')) -->ab cdefg
print(string_insert('00abcdefg',3,' ', "00")) -->00ab cdefg