Fun with strings
Weekly challenge 369 — 13 April 2026
Week 369: 13 Apr 2026
You are given a string, group size and filler character.
Write a script to divide the string into groups of the given size. In the last group if the string doesn’t have enough characters remaining fill with the given filler character.
Example 1 Input: $str = 'RakuPerl', $size = 4, $filler = '*' Output: ('Raku', 'Perl') Example 2 Input: $str = 'Python', $size = 5, $filler = '0' Output: ('Pytho', 'n0000') Example 3 Input: $str = '12345', $size = 3, $filler = 'x' Output: ('123', '45x') Example 4 Input: $str = 'HelloWorld', $size = 3, $filler = '_' Output: ('Hel', 'loW', 'orl', 'd__') Example 5 Input: $str = 'AI', $size = 5, $filler = '!' Output: 'AI!!!'
Let's start by adding $size times $filler to
the end of $string - unless $string is an exact
multiple of $size long.
Now all we have to do is successively chop $size
characters from string. It doesn't matter if
there a a few filler characters left at the end.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2026-04-13 use utf8; # Week 369 - task 2 - Group division use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; group_division('RakuPerl', 4, '*'); group_division('Python', 5, '0'); group_division('12345', 3, 'x'); group_division('HelloWorld', 3, '_'); group_division('AI', 5, '!'); sub group_division { my ($string, $size, $filler, $output); # initialise ($string, $size, $filler) = @_; say qq[\nInput: \$string = '$string', \$size = $size, \$filler = '$filler']; # append $filler x $size unless length is a multiple of $size $string .= $filler x $size unless length($string) % $size == 0; # match characters $size at a time $output .= qq['$1', ] while $string =~ m|(.{$size})|g; # report say qq[Output: ] . substr($output, 0, -2); }
last updated 2026-04-13 — 7 lines of code
Input: $string = 'RakuPerl', $size = 4, $filler = '*' Output: 'Raku', 'Perl' Input: $string = 'Python00000', $size = 5, $filler = '0' Output: 'Pytho', 'n0000' Input: $string = '12345xxx', $size = 3, $filler = 'x' Output: '123', '45x' Input: $string = 'HelloWorld___', $size = 3, $filler = '_' Output: 'Hel', 'loW', 'orl', 'd__' Input: $string = 'AI!!!!!', $size = 5, $filler = '!' Output: 'AI!!!'
Any content of this website which has been created by Peter Campbell Smith is in the public domain