I’ve recently been creating a system in which changes a chat. However, I’ve realized they use spaces to separate the positions of the username and text itself, I wish to preserve these spaces so that I can freely edit the text.
To put it simply,
I wish to take a string which has a lot of spaces before it, and then edit that string, but keep the spaces (The spaces are at a randomized amount, and are always before the string itself)
For example: "-" will mean space due to formatting
“--------------------Hi there!”
I wish to edit it to: “--------------------Bye then!”
Is there some form of string technique I can use to see where the spaces end and then edit the string that comes after the spaces?
I had fun brushing up on my use of “magic” characters, or string patterns.
function manipulateMessage(message)
--"+" is a magic character that will match 1 or more of the preceding character
local spaceStart, spaceEnd = string.find(message, " +")
-- Check to make sure spaces start at the front, and that the entire message isn't only spaces.
if spaceStart == 1 and spaceEnd < string.len(message) then
local spacesString = string.sub(message, spaceStart, spaceEnd)
local textString = string.sub(message, spaceEnd+1)
-- Do custom manipulation here
local newTextString = textString
if textString == 'Hi there!' then
newTextString = 'Bye then!'
end
return spacesString..newTextString
end
return message
end
local input = " Hi there!"
local output = manipulateMessage(input)
print('input :', input)
print('output:', output)