How to insert a character into the middle of a string?

Hi,

I’d like to be able to add a : into the middle of a 4-character string. How would I go about doing this?
For example, 1234 would turn into 12:34

Thanks

1 Like

Honestly, there may be a lot of ways to do it. But I personally think the simplest way would just use substring which would look something like this:

local myString = 1234
local half = math.floor(len(myString)/2)

local newString = string.sub(myString, 1, half)..":"..string.sub(myString, half, len(myString))

If substring behaves the same in Java as Lua, then it should give the result you desired.
And if you’d like more information on string manipulation, here’s a link

local text = '1234'

function split(arg)
	local len = string.len(arg)
	local firstHalf = string.sub(arg, 1, len/2)
	local secondHalf = string.sub(arg, (len/2) + 1, len)
	return firstHalf .. ':' .. secondHalf
end

local String = split(text)
1 Like

Hi, thanks for your answer

I tried it and it appears to somewhat work, although it hasn’t split it correctly, my output now is 12:234.
Any ideas?

1 Like

Hey, thanks for your response, unfortunately your method has also seemed to return the same result as @1x_Gacha 's, with it returning 12:234 instead of 12:34.

My code should work now I forgot to add the + 1 on the secondHalf variable

1 Like