The Weekly Challenge 369

Social Media Tags & String Grouping!

Original Challenge Link

Task 1: Valid Tag

"Hashtag Hero: Cleaning Captions for Social Media!"

Given a video caption, we need to generate a sanitized hashtag in three steps: convert to camelCase, remove non-alphabetic characters, and truncate to 100 characters (including the # prefix).

The Strategy: First, remove all characters that are not letters or spaces to preserve word boundaries. Convert the string to lowercase. Use a regex to find spaces followed by a letter and uppercase that letter (camelCase). Finally, remove all remaining spaces, truncate the string if it exceeds 99 characters, and prepend the # symbol.
Perl Implementation
sub generate_tag {
    my ($caption) = @_;

    $caption =~ s/[^a-zA-Z\s]//g;
    $caption =~ s/^\s+//;
    $caption = lc($caption);

    # camelCase: space(s) followed by a letter becomes uppercase letter
    $caption =~ s/\s+([a-z])/\U$1/g;

    # Remove any remaining spaces
    $caption =~ s/\s+//g;

    # Enforce Length
    if (length($caption) > 99) {
        $caption = substr($caption, 0, 99);
    }

    return '#' . $caption;
}
Python Implementation
def generate_tag(caption: str) -> str:
    # Sanitise (keep letters and spaces)
    caption = re.sub(r'[^a-zA-Z\s]', '', caption)
    caption = caption.lstrip().lower()

    # Format as camelCase
    caption = re.sub(r'\s+([a-z])', lambda m: m.group(1).upper(), caption)

    # Remove remaining spaces
    caption = re.sub(r'\s+', '', caption)

    # Enforce Length
    if len(caption) > 99:
        caption = caption[:99]

    return '#' + caption

Task 2: Group Division

"Perfect Packing: Dividing Strings into Equal Groups!"

Divide a string into segments of a given size. If the last segment is too short, pad it with a provided filler character.

The Strategy: First, calculate how many characters are needed to make the string length a multiple of the group size. Append the filler character that many times. Then, use a simple loop or a global regex match to extract segments of the specified size.
Perl Implementation
sub divide_groups {
    my ($str, $size, $filler) = @_;

    return [ $filler x $size ] if $str eq '';

    my $remainder = length($str) % $size;
    if ($remainder > 0) {
        $str .= $filler x ($size - $remainder);
    }

    my @groups = $str =~ /(.{$size})/g;
    return \@groups;
}
Python Implementation
def divide_groups(text: str, size: int, filler: str) -> list[str]:
    if not text:
        return [filler * size]

    remainder = len(text) % size
    if remainder > 0:
        text += filler * (size - remainder)

    return [text[i:i + size] for i in range(0, len(text), size)]