Start learning free

LESSON 221 OF 291 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Capitalize Each Word in Scala: split, substring and mkString

Practice Read the full explanation

Given a string sentence, return the same sentence with the first letter of each word in upper case.

The words are separated by single spaces, and the sentence doesn't start or end with a space. Only the first character of each word changes: the rest of the word stays exactly as it is, even when it has upper-case letters. A first character that has no upper case, like a digit, stays as it is too.

 

Example 1:

Input: sentence = "hello world"
Output: "Hello World"
Explanation: h becomes H and w becomes W.

Example 2:

Input: sentence = "learn to code with AlgoCademy"
Output: "Learn To Code With AlgoCademy"
Explanation: AlgoCademy already starts with an upper-case letter, so it stays the same.

Example 3:

Input: sentence = "iPhone and NASA"
Output: "IPhone And NASA"
Explanation: Only the first character of each word changes: "Phone" and "ASA" stay as they were.

 

Constraints:

  • sentence has at least one word.
  • sentence contains English letters, digits and apostrophes, with single spaces between the words.
STEP 1 OF 6
    Ctrl + Enter to check

    SCALA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Capitalize Each Word in Scala, explained

    Problem overview

    The function capitalizeWords takes a string sentence and returns it with the first letter of each word in upper case. Words are separated by single spaces, and the sentence neither starts nor ends with a space. Only the first character of a word changes. The rest of the word stays exactly as it is, even when it already has upper-case letters, and a first character that has no upper case, such as a digit, stays too.

    "hello world" becomes "Hello World". "learn to code with AlgoCademy" becomes "Learn To Code With AlgoCademy": AlgoCademy already starts with a capital. "iPhone and NASA" becomes "IPhone And NASA", because only the first character of each word is touched.

    Approach

    Break the sentence into words, fix each word on its own, and glue the words back together. This is a common shape for text problems: split, transform each piece, join.

    To fix one word, cut it into its first character and the rest. The first character is converted to upper case, and the rest is appended without any change. Leaving the rest alone is what keeps NASA from turning into Nasa.

    Step by step

    1. Split the sentence at the spaces with sentence.split(" ") and store the result in val words. For "hello world" that is the two words hello and world.
    2. Create val result as an empty ArrayBuffer[String], written with its full package path, scala.collection.mutable.ArrayBuffer. It is a val because the buffer itself isn't replaced, only grown.
    3. Write a for loop with a variable word over words.
    4. Inside, build capitalized: the first character, word.substring(0, 1), converted with toUpperCase, followed by word.substring(1), everything after it.
    5. Append capitalized to result with +=.
    6. After the loop, return result.mkString(" "). It joins the buffer's strings with a single space between each two.

    For "iPhone and NASA" the words are iPhone, and and NASA. They become IPhone, And and NASA, and the joined result is IPhone And NASA.

    The solution in Scala

    class Solution {
        def capitalizeWords(sentence: String): String = {
            val words = sentence.split(" ")
            val result = scala.collection.mutable.ArrayBuffer[String]()
            for (word <- words) {
                val capitalized = word.substring(0, 1).toUpperCase + word.substring(1)
                result += capitalized
            }
            return result.mkString(" ")
        }
    }
    

    Details that matter in Scala:

    • substring(0, 1) takes the characters from index 0 up to, but not including, index 1: one character. substring(1) takes everything from index 1 to the end. For a one-letter word, such as a, substring(1) is an empty string, so the code works without a special case.
    • toUpperCase returns a new string. Strings are immutable, so the original word isn't changed. A digit stays as it is: "3d".substring(0, 1).toUpperCase is "3".
    • split(" ") returns an Array[String], and for (word <- words) visits its elements in order.
    • mkString(" ") takes the separator. It puts it between the elements only, so there is no trailing space. For example, Array("a", "b").mkString("[", "|", "]") gives [a|b].
    • A val holding an ArrayBuffer can still grow: val stops you from reassigning result, not from adding to the buffer.

    Edge cases and common mistakes

    • Upper-casing the whole word. Calling toUpperCase on the whole word turns AlgoCademy into ALGOCADEMY. Only the first character should change.
    • Lower-casing the rest. That would turn NASA into Nasa, which the task doesn't ask for.
    • A word that starts with a digit. 3d printing becomes 3d Printing.
    • Extra spaces. The lesson promises single spaces. If a sentence had two in a row, split(" ") would produce an empty word in between: "hello world".split(" ") gives hello, an empty string and world.

    Testing

    capitalizeWords("hello world")                   -> Hello World
    capitalizeWords("learn to code with AlgoCademy") -> Learn To Code With AlgoCademy
    capitalizeWords("iPhone and NASA")               -> IPhone And NASA
    capitalizeWords("a b")                           -> A B
    capitalizeWords("3d printing")                   -> 3d Printing
    
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free