DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #190 - capitalizeFirstLast

For this challenge, you will have to write a function called capitalizeFirstLast or capitalize_first_last. This function will capitalize the first and last letter of each word, and lowercase what is in between.

capitalizeFirstLast "and still i rise" -- "AnD StilL I RisE"

Rules:

  • The function will take a single parameter, which will be a string.
  • The string can contain words separated by a single space.
  • Words are made of letters from the ASCII range only.
  • The function should return a string.
  • Only the first and last letters are uppercased.
  • All the other letters should be lowercased.

Examples:

capitalizeFirstLast "and still i rise"               -- "AnD StilL I RisE"
capitalizeFirstLast "when words fail music speaks"   -- "WheN WordS FaiL MusiC SpeakS"
capitalizeFirstLast "WHAT WE THINK WE BECOME"        -- "WhaT WE ThinK WE BecomE"
capitalizeFirstLast "dIe wITh mEMORIEs nOt dREAMs"   -- "DiE WitH MemorieS NoT DreamS"
capitalizeFirstLast "hello"                          -- "HellO"

Good luck!


This challenge comes from aminnairi here on DEV. Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Latest comments (24)

Collapse
 
florincornea profile image
Cornea Florin
Collapse
 
madstk1 profile image
Natamo

Not the best-looking of all, but it works. C#, with a lot of fiddling with Join and Select.

public static string CapitalizeFirstLast(this string input) => String.Join(" ", input.Split(" ").Select(sub => new string(String.Join("", sub.ToLower().ToCharArray().Select((v, k) => (k == 0 || k == sub.Length - 1) ? Char.ToUpper(v) : Char.ToLower(v))))));

And, to test it.

string[] testStrings = {
    "and still i rise",
    "when words fail music speaks",
    "WHAT WE THINK WE BECOME",
    "dIe wITh mEMORIEs nOt dREAMs",
    "hello"
};

foreach(string s in testStrings) {
    Console.WriteLine(s.CapitalizeFirstLast());
}
Collapse
 
pdandy profile image
Andy Thompson

Came up with this Elm solution while I was procrastinating at work today:

capitalizeFirstLast : String -> String
capitalizeFirstLast input =
  let
    capitalizeFirst = String.left 1 >> String.toUpper
    capitalizeLast  = String.right 1 >> String.toUpper
    lowercaseMiddle = String.slice 1 -1 >> String.toLower
    transform word  =
      if String.length word < 2 then
        String.toUpper word
      else
        capitalizeFirst word ++ lowercaseMiddle word ++ capitalizeLast word
  in
  String.words input
    |> List.map transform
    |> String.join " "

Not overly different from the other solutions here, but neat nonetheless.

Collapse
 
maskedman99 profile image
Rohit Prasad

Python

var = input("Enter the String: ")

def capitalizeFirstLast(x):
        x = x.lower()
        x = list(x)
        x[0] = x[0].upper()
        x[len(x)-1] = x[len(x)-1].upper()

        for i in range(len(x)):
                if x[i] == ' ':
                        x[i-1] = x[i-1].upper()
                        x[i+1] = x[i+1].upper()

        return(''.join(x))

print(capitalizeFirstLast(var))
Collapse
 
navdeepsingh profile image
Navdeep Singh • Edited
console.clear();
const capitalizeFirstLast = (str) => {
  let strArr = str.split(" ");
  let parseStr = strArr.map(item => {
        itemArr = [...item];
        midStr = itemArr.slice(1,itemArr.length-1).join('');
        return item.length > 1 ? item[0].toUpperCase() + midStr.toLowerCase() + item[item.length-1].toUpperCase() : item[0].toUpperCase();      
  }).join(' ');
  console.log(parseStr);  
}
capitalizeFirstLast('my name is NAVDEEP singh')

JSBin Link

Collapse
 
amcmillan01 profile image
Andrei McMillan

python

import re


def to_uc(match_group):
    return match_group.group(0).upper()


def capitalize_first_last(in_str):
    in_str = in_str.lower().strip()
    in_str = re.sub(r'\s+', ' ', in_str)
    in_str = re.sub(r'(^[a-z])', to_uc, in_str)
    in_str = re.sub(r'([a-z]$)', to_uc, in_str)
    in_str = re.sub(r'(\s[a-z])', to_uc, in_str)
    in_str = re.sub(r'([a-z]\s)', to_uc, in_str)

    print in_str


# -----
capitalize_first_last('and still i    rise')
capitalize_first_last('when words fail music speaks')
capitalize_first_last('WHAT WE THINK WE BECOME')
capitalize_first_last('dIe wITh mEMORIEs nOt dREAMs')
capitalize_first_last('hello')

# -----
# AnD StilL I RisE
# WheN WordS FaiL MusiC SpeakS
# WhaT WE ThinK WE BecomE
# DiE WitH MemorieS NoT DreamS
# HellO

Collapse
 
craigmc08 profile image
Craig McIlwrath • Edited

Haskell

import Data.Char (toUpper, toLower)

capitalizeFirstLast :: String -> String
capitalizeFirstLast = unwords . map f . words
  where f (c:[]) = [toUpper c]
        f (c:cs) = toUpper c : map toLower (init cs) ++ [toUpper (last cs)]
Collapse
 
willsmart profile image
willsmart • Edited

An easy option is to start off by lowercasing the whole thing...
(JS)

capitalizeFirstLast = s => s.toLowerCase().replace(/\b\w|\w\b/g, c => c.toUpperCase())

Regex matches single letters preceded by a word boundary or followed by a word boundary.

Running through the examples:

[
  "and still i rise",
  "when words fail music speaks",
  "WHAT WE THINK WE BECOME",
  "dIe wITh mEMORIEs nOt dREAMs",
  "hello"
].map(s => `"${s}" -> "${capitalizeFirstLast(s)}"`).join("\n")

>> 

"and still i rise" -> "AnD StilL I RisE"
"when words fail music speaks" -> "WheN WordS FaiL MusiC SpeakS"
"WHAT WE THINK WE BECOME" -> "WhaT WE ThinK WE BecomE"
"dIe wITh mEMORIEs nOt dREAMs" -> "DiE WitH MemorieS NoT DreamS"
"hello" -> "HellO"
Collapse
 
khauri profile image
Khauri

Nice! Super clean.

Collapse
 
willsmart profile image
willsmart

Thanks!

Collapse
 
khauri profile image
Khauri • Edited

Javascript + Regex "One" liner.

function capitalizeFirstLast(string) {
  return string.replace(/(\w)((\w*)(\w))?/g, (_, a, __, b, c) => [a.toUpperCase(), b && b.toLowerCase(), c && c.toUpperCase()].filter(Boolean).join(''))
}

Click here if you're curious what the regular expression does

Collapse
 
jehielmartinez profile image
Jehiel Martinez

JAVASCRIPT ANSWER

function capitalizeFirstLast(str) {
    return str.replace(/[^\s]+/g, (match) => {
        replaceStr = '';
        const len = match.length;

        for(i=0; i<len; i++){
            if(i === 0 || i === len-1){
                replaceStr = replaceStr + match[i].toUpperCase();
            } else {
                replaceStr = replaceStr + match[i].toLowerCase();
            }
        }

        return replaceStr
    });
};