How to split strings into equal parts?

I just want to split a large amount of text into equal parts.

3 Likes

You can split strings by using string.split.

Example:

local mylString = "Hello :World!:"
print(string.split(myString, ":"))

--[[
   Output: {
     [1] = "Hello",
     [2] = "World!"
   } 
--]]

Maybe tell him what : is?

It’s a separator so you don’t just have to use it. Separator could be anything.

I know about this. What I meant is like for example I have a large amount of string, and I want to into 3 equal parts or 10 equal parts. How do I do that?

this is what i got working using the help of ChatGPT.

local inputString = "YourString"
local stringLength = #inputString
local numParts = 3 -- Number of parts to split the string into

local partSize = math.floor(stringLength / numParts) -- Calculate the size of each part

local parts = {} -- Table to store the split parts

for i = 1, numParts do
    local startIndex = (i - 1) * partSize + 1
    local endIndex = i * partSize
    if i == numParts then
        endIndex = stringLength -- For the last part, take the remaining characters
    end

    local part = string.sub(inputString, startIndex, endIndex)
    table.insert(parts, part)
end

for i, part in ipairs(parts) do
    print("Part " .. i .. ": " .. part)
end

Do you want a certain number of parts, or do you want parts of certain lengths? Some example inputs and outputs would be helpful.

Edit: If it’s the latter, then this should work:

type stringArray = {[number]: string}
function partitionString(input: string, partitionLength: number): stringArray
	local array = {}
	for i = 1, #input, partitionLength do
		table.insert(array, input:sub(i, i + partitionLength - 1))
	end
	return array
end
print(partitionString("hi guys", 2)) -- {"hi, " g", "uy", "s"}
print(partitionString("hello world", 3)) -- {"hel", "lo ", "wor", "ld"}
local splitSize = 5
local text = "Hello there :)"

local parts = {}
for i = 1, text:len(), splitSize do
	local part = text:sub(i, i+splitSize-1)
	table.insert(parts, part)
end

--this will add spaces to the last part until it matches the wanted length
parts[#parts] ..= string.rep(" ", splitSize-parts[#parts]:len())

print(parts)

Also, if you want a small function for it:

function getParts(s: string, x: number, addSpaces: boolean?): {string}
	local p = {}
	for i = 1, s:len(), x do table.insert(p, s:sub(i, i+x-1)) end
	if addSpaces then p[#p] ..= string.rep(" ", x-p[#p]:len()) end
	return p
end

print(getParts("Hello there :)", 5, true))