DEV Community

dev.to staff
dev.to staff

Posted on

12 4

Daily Challenge #180 - SMS Shortener

Setup

SMS messages are limited to 160 characters. It tends to be irritating, especially when freshly written message is 164 characters long. Implement a function to shorten the message to 160 characters, starting from the end, by replacing spaces with camelCase, as much as necessary.

Example

Original Message:
No one expects the Spanish Inquisition! Our chief weapon is surprise, fear and surprise; two chief weapons, fear, surprise, and ruthless efficiency! And that will be it.

Shortened Message:
No one expects the Spanish Inquisition! Our chief weapon is surprise, fear and surprise; two chief weapons, fear,Surprise,AndRuthlessEfficiency!AndThatWillBeIt.

Tests

"SMS messages are limited to 160 characters. It tends to be irritating, especially when freshly written message is 164 characters long. SMS messages are limited to 160 characters. It tends to be irritating, especially when freshly written message is 164 characters long."

"This message is already short enough!"

"ThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoonThereIsNoSpoon"

Good luck!


This challenge comes from Bugari on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (6)

Collapse
 
jehielmartinez profile image
Jehiel Martinez

js recursive

function shortener(str) {
    const regex = /\s+(\S*)$/g;

    if(str.length <= 160){
        return str;
    };

    let match = str.match(regex);
    if(!match){
        return 'No place to trim'
    }

    let trimmed = match[0].trim();
    let capital = trimmed.replace(/^./, trimmed[0].toUpperCase());

    return shortener(str.replace(regex, capital));
};
Collapse
 
avaq profile image
Aldwin Vlasblom • Edited

A recursive solution in JavaScript:

const pattern = /\s+(\S)(\S*)$/;
const minify = sms => 
  sms.length <= 160 || sms.match (pattern) === null ? sms :
  minify (sms.replace (pattern, (_, c, w) => c.toUpperCase() + w))

With comments:

// A regular expression that matches any white-space followed by a captured 
// non-white-space character, and any number of non white-space characters
// separately captured, all at the end of the input.
const pattern = /\s+(\S)(\S*)$/;

const minify = sms =>
  // If the input SMS is already short enough, or has no white-space
  // characters, we just return it.
  sms.length <= 160 || sms.match (pattern) === null ? sms :

  // If it does have white-space, we remove the last occurrence and
  // uppercase the captured character. Then we minify the resulting
  // SMS recursively.
  minify (sms.replace (pattern, (_, c, w) => c.toUpperCase() + w))
Collapse
 
exts profile image
Lamonte

This one almost stumped me ngl lol

Dart

String smsShortener(String message) {
  if(message.length <= 160) return message;

  List<String> spaces = message.split(" ");
  var result = message;
  for(var idx = spaces.length-1; idx > 0; idx--) {
    var start = spaces.take(idx).join(" ");
    var end = spaces.skip(idx).map((word) => "${word[0].toUpperCase()}${word.substring(1)}").join("");
    result = "$start$end";
    if(result.length <= 160) return result;
  }
  return result.substring(0, 160);
}
Collapse
 
korguy profile image
KORguy • Edited

python solution

def SMS_shortner(msg):
    while len(msg) > 160:
        try:
            lst = msg.split(" ")
            lst.append(lst.pop(-2) + lst.pop().title())
            msg = " ".join(lst)
        except IndexError:
            print("Text can not be shortened.")
    return msg
Collapse
 
cipharius profile image
Valts Liepiņš

This one ended up being less readable, will give a compact version and expanded version with commentary. Once again, Ruby:

def shortenSMS str
    [str.length - 160, str.count(' ')].min.times do
        str.sub!(/\s(\S*)$/) { $1[0].upcase + $1[1..] }
    end
    str[0...160]
end

Explained version:

def shortenSMS str
    # Get basic message statistics
    excessChars = str.length - 160
    spacesCount = str.count(' ')
    # How many substitutions should be done
    subCount = [excessChars, spacesCount].min

    subCount.times do
        # Substitutes with mutation first space from end, capturing the tail
        str.sub!(/\s(\S*)$/) do
            # Upcase first character of tail and append rest
            # $1.capitalize won't do, because it lowercases rest of the string
            $1[0].upcase + $1[1..]
        end
    end
    # Ensure that message is 160 chars long
    str[0...160]
end

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay