1. Post #1
    Gold Member
    Entoros's Avatar
    October 2008
    2,318 Posts
    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","!"}

    Edited:

    Never mind, fixed.

    function CutStr(str,num)
    	local ret = ""
    	for i = 1, string.len(str), num do
    		ret = ret..string.sub(str,i,i+num-1).."\n"
    	end
    	return ret
    end

    By the way.

  2. Post #2
    Gold Member
    Kogitsune's Avatar
    September 2005
    2,796 Posts
    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
    
    x = "This is a string!"
    for k, v in ipairs( x:chunk( 3 ) ) do
      print( v )
    end
    
    As an alternate.

  3. Post #3
    Gold Member
    Entoros's Avatar
    October 2008
    2,318 Posts
    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?

  4. Post #4
    Gold Member
    Nevec's Avatar
    June 2008
    1,091 Posts
    '.' 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..

    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 > 0 ) then table.insert( output, str ); end
    	
    	return output;
    	
    end
    

    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..

    function string.split( str, size )
    	
    	local output = { };
    	
    	for match in str:gmatch( "."..string.rep( ".?", size - 1 ) ) do
    		
    		if( #match > 0 ) then table.insert( output, match ); end
    		
    	end
    	
    	return output;
    	
    end
    

  5. Post #5
    Gold Member
    Kogitsune's Avatar
    September 2005
    2,796 Posts
    Whoops, wasn't thinking too clearly when I wrote that. Thanks for fixing it.