Last word, buddy
Weekly challenge 331 — 21 July 2025
Week 331: 21 Jul 2025
You are given a string. Write a script to find the length of the last word in the given string.
Example 1 Input: $str = 'The Weekly Challenge' Output: 9 Example 2 Input: $str = ' Hello World ' Output: 5 Example 3 Input: $str = 'Let's begin the fun' Output: 3
Well, this isn't too hard. We're looking for a string of letters, followed by 0 or more non-letters and the end of the string, which is easy to say in regular-expressionese.
The only slight edge case is when there are no words at all in the string.
#!/usr/bin/perl # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge use v5.26; # The Weekly Challenge - 2025-07-21 use utf8; # Week 331 - task 1 - Last word use warnings; # Peter Campbell Smith binmode STDOUT, ':utf8'; use Encode; last_word('The Weekly Challenge'); last_word(' Hello World '); last_word('123 4567'); last_word(''); last_word('Danger!'); sub last_word { $_[0] =~ m|([a-z]+)[^a-z]*$|i; say qq[\nInput: '$_[0]']; say qq[Output: ] . (defined($1) ? length($1) : 0); }
Input: 'The Weekly Challenge' Output: 9 Input: ' Hello World ' Output: 5 Input: '123 4567' Output: 0 Input: '' Output: 0 Input: 'Danger!' Output: 6
Any content of this website which has been created by Peter Campbell Smith is in the public domain