Keeper
Keeper

Reputation: 960

Split string in equal chunks in Lua

I need to split a string in equal sized chunks (where the last chunk can be smaller, if the strings length can't be divided without remainder).

Let's say I have a string with 2000 chars. I want to split this string in equal sized chunks of 500 chars, so I would end up with 4 strings of 500 chars.

How can this be done in Lua, when neither the length of the initial string is fixed, nor the chunk size?

Example

String: "0123456789" (Length = 10) should be splitted in strings of 3 characters

Result: "012", "345", "678", "9"

(doesn't matter if the result is in a table or returned by a iterator)

Upvotes: 3

Views: 5852

Answers (3)

rsc
rsc

Reputation: 10669

local function splitByChunk(text, chunkSize)
    local s = {}
    for i=1, #text, chunkSize do
        s[#s+1] = text:sub(i,i+chunkSize - 1)
    end
    return s
end

-- usage example
local st = splitByChunk("0123456789",3)
for i,v in ipairs(st) do
   print(i, v)
end

-- outputs
-- 1    012
-- 2    345
-- 3    678
-- 4    9

Upvotes: 7

Etan Reisner
Etan Reisner

Reputation: 80921

> function tt(s)
>>     local t={}
>>     for p in s:gmatch("..?.?") do
>>         t[#t+1]=p
>>     end
>>
>>     for i,v in ipairs(t) do
>>         print(i, v)
>>     end
>> end
> tt("0123")
1       012
2       3
> tt("0123456789")
1       012
2       345
3       678
4       9
> tt("012345678901")
1       012
2       345
3       678
4       901

Upvotes: 0

Yu Hao
Yu Hao

Reputation: 122383

To split a string into 4, you can get the size like this:

local str = "0123456789" 
local sz = math.ceil(str:len() / 4)

Then the first string is str:sub(1, sz), I'll leave the rest to you.

Upvotes: 5

Related Questions