More strings and arrays
Weekly challenge 322 — 19 May 2025
Week 322: 19 May 2025
You are given a string and a positive integer. Write a script to format the string, removing any dashes, in groups of size given by the integer. The first group can be smaller than the integer but should have at least one character. Groups should be separated by dashes.
Example 1 Input: $str = 'ABC-D-E-F', $i = 3 Output: 'ABC-DEF' Example 2 Input: $str = 'A-BC-D-E', $i = 2 Output: 'A-BC-DE' Example 3 Input: $str = '-A-B-CD-E', $i = 4 Output: 'A-BCDE'
Once more, there is probably a one-liner to be had, but my solution is:
$string
.
$count
characters from the end of $string
and
add them to the beginning of $result
, each preceded by '-'.
$string
, add it to the start of $result
This works even if there are no '-' characters in $string
,
or if $string
comprises only '-' characters.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-05-19 use utf8; # Week 322 - task 1 - String format use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; string_format('ABC-D-E-F', 3); string_format('A-BC-D-E', 2); string_format('-A-B-CD-E', 4); string_format('AAA', 1); string_format('TEA-TEA-TEA-TEA', 3); string_format('pe-rlwe-ek03-22ta-sk00-01', 4); string_format('---', 1); sub string_format { my($string, $count, $result); # initialise ($string, $count) = @_; say qq[\nInput: \$string = '$string', \$count = $count]; $result = ''; # get rid of existing '-' characters $string =~ s|-||g; if ($string) { # add successive groups of final $count letters to $result $result = qq[-$1$result] while $string =~ s|(\w{$count})$||g; # if anything left, add it, else remove leading '-' $result = $string ? qq[$string$result] : substr($result, 1); } say qq[Output: '$result']; }
Input: $string = 'ABC-D-E-F', $count = 3 Output: 'ABC-DEF' Input: $string = 'A-BC-D-E', $count = 2 Output: 'A-BC-DE' Input: $string = '-A-B-CD-E', $count = 4 Output: 'A-BCDE' Input: $string = 'AAA', $count = 1 Output: 'A-A-A' Input: $string = 'TEA-TEA-TEA-TEA', $count = 3 Output: 'TEA-TEA-TEA-TEA' Input: $string = 'pe-rlwe-ek03-22ta-sk00-01', $count = 4 Output: 'perl-week-0322-task-0001' Input: $string = '---', $count = 1 Output: ''
Any content of this website which has been created by Peter Campbell Smith is in the public domain