Peter
Peter Campbell Smith

Pairs, sriap and
MsEtRrGiEngs

Weekly challenge 256 — 12 February 2024

Week 256 - 12 Feb 2024

Task 2

Task — Merge strings

You are given two strings, $str1 and $str2. Write a script to merge the given strings by adding in alternative order starting with the first string. If one string is longer than the other then append the remaining at the end.

Examples


Example 1
Input: $str1 = "abcd", $str2 = "1234"
Output: "a1b2c3d4"

Example 2
Input: $str1 = "abc", $str2 = "12345"
Output: "a1b2c345"

Example 3
Input: $str1 = "abcde", $str2 = "123"
Output: "a1b2c3de"

Analysis

You can access the characters of a string one by one using substr, but I feel it is cleaner to use split to split the letters into two arrays. The result string is then obtained by adding characters alternately from each array - if they exist - and stopping when it is the same length as the sum of the lengths of the input strings.

Try it 

Try running the script with any input:



example: 12345



example: abcdefg

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2024-02-12
use utf8;     # Week 256 - task 2 - Merge strings
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

merge_strings('abcdefg', 'zyxwvut');
merge_strings('abcde', 'DEFGHIJK');
merge_strings('', '');
merge_strings('Pr ekyCalne', 'elWel hleg');

sub merge_strings {
    
    my (@a, @b, $c, $j, $c_last);
    
    # split the strings into array
    @a = split('', $_[0]);
    @b = split('', $_[1]);
    $c = '';
    $c_last = scalar @a + scalar @b - 1;
    
    # form the result by zipping them together
    for $j (0 .. 9999) {
        $c .= $a[$j] if $j < scalar @a;
        $c .= $b[$j] if $j < scalar @b;
        last if $j == $c_last;
    }
    
    # and show the result
    say qq[\nInput:  \$str1 = '$_[0]', \$str2 = '$_[1]'];
    say qq[Output: '$c'];   
}

Output


Input:  $str1 = 'abcdefg', $str2 = 'zyxwvut'
Output: 'azbycxdwevfugt'

Input:  $str1 = 'abcde', $str2 = 'DEFGHIJK'
Output: 'aDbEcFdGeHIJK'

Input:  $str1 = '', $str2 = ''
Output: ''

Input:  $str1 = 'Pr ekyCalne', $str2 = 'elWel hleg'
Output: 'Perl Weekly Challenge'