Separating strings every n characters

The title pretty much says it. I want to cut a string every n characters, so something like

string.cut(“This is a string!”,3)

returns {“Thi”,“s i”,“s a”,“str”,“ing”,"!"}

[editline]01:08PM[/editline]

Never mind, fixed.

[lua]function CutStr(str,num)
local ret = “”
for i = 1, string.len(str), num do
ret = ret…string.sub(str,i,i+num-1)…"
"
end
return ret
end[/lua]

By the way.

[lua]function string.chunk( str, n )
local k, t

``````t= { }

for k in str:gmatch( string.rep( ".", n ) ) do
table.insert( t, k )
end

return t
``````

end
[/lua]
[lua]
x = “This is a string!”
for k, v in ipairs( x:chunk( 3 ) ) do
print( v )
end
[/lua]
As an alternate.

Line 6, “for k in str:gmatch( string.rep( “.”, n ) ) do”, how exactly does that work?

If I understand it correctly, “.” represents a word, then you repeat it based on n (the number of words to put in a chunk), and gmatch finds that pattern?

‘.’ represents a single character. ‘string.rep’ repeats it n times, so that the outcome pattern will match n chars.

There’s a little problem with Kogitsune’s code, though. It will only match n characters and not less. This one will split the string properly…

[lua]
function string.chop( str, size )

``````local output = { };

local pattern = string.rep( ".", size );
str = str:gsub( pattern, function( part ) table.insert( output, part ); return ""; end );

if( #str &gt; 0 ) then table.insert( output, str ); end

return output;
``````

end
[/lua]

Here’s a library with some useful string functions if you need anything else.

Edit:

Ha. Actually, you can use Kogitsune’s code, but with a different pattern. You can use the ‘?’ repetition which will match zero or one rep…

[lua]
function string.split( str, size )

``````local output = { };

for match in str:gmatch( "."..string.rep( ".?", size - 1 ) ) do

if( #match &gt; 0 ) then table.insert( output, match ); end

end

return output;
``````

end
[/lua]

Whoops, wasn’t thinking too clearly when I wrote that. Thanks for fixing it.