Start learning free

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

Capitalize Each Word in Kotlin: split, uppercase and joinToString

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

    KOTLIN · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Capitalize Each Word in Kotlin, explained

    Problem overview

    The function capitalizeWords receives a sentence and returns it with the first letter of each word in upper case. Words are separated by single spaces, and the sentence has no space at the start or end. Only the first character of each word changes. The rest stays exactly as it is, even upper-case letters, and a first character with 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". "iPhone and NASA" becomes "IPhone And NASA": the i changes, while the "Phone" and "ASA" parts stay as they were.

    Approach

    Break the sentence into words, fix each word, and glue the words back together. The three tools are split(" "), which cuts a string at each space and gives a list of words, substring and uppercase() for fixing a word, and joinToString(" "), which joins a list into one string with a separator between items.

    Splitting "hello world" gives [hello, world]. Rebuilding each word as upper-case first letter plus the rest gives [Hello, World], and joining with a space gives "Hello World".

    Step by step

    1. Split the sentence into a val words with split(" "). Single spaces between words mean the pieces are exactly the words.
    2. Create an empty list for the results: val result = mutableListOf<String>(). val is fine, since the list itself changes while the variable keeps pointing at the same list.
    3. Loop over the words with for (word in words).
    4. Build the capitalized word. word.substring(0, 1) is the first character, uppercase() converts it, and word.substring(1) is everything after it. Add the two parts together.
    5. Add it to result.
    6. Return result.joinToString(" "). Splitting at single spaces and joining with single spaces puts every space back where it was.

    The solution in Kotlin

    class Solution {
        fun capitalizeWords(sentence: String): String {
            val words = sentence.split(" ")
            val result = mutableListOf<String>()
            for (word in words) {
                val capitalized = word.substring(0, 1).uppercase() + word.substring(1)
                result.add(capitalized)
            }
            return result.joinToString(" ")
        }
    }
    

    Some details worth knowing:

    • substring(start, end) takes the characters from start up to but not including end, so substring(0, 1) is the first character. substring(1) runs to the end of the string.
    • A one-letter word works. "a".substring(1) is the empty string, because the start index equals the length. The result is "A".
    • uppercase() returns a new string. Strings can't be changed in place. Characters with no upper case, such as the 3 in "3d printing", come back unchanged, so the result is "3d Printing".
    • uppercase() versus capitalize(). The older capitalize() is deprecated in current Kotlin. uppercase() is the current name for upper-casing a string.
    • + joins strings. "H" + "ello" is "Hello".

    Complexity

    Time is O(n) for a sentence of n characters: splitting, copying each word and joining each touch every character a constant number of times. Space is O(n) for the list of words and the result list.

    Edge cases and common mistakes

    • Upper-casing the whole word. That would turn "NASA" into itself but "iPhone" into "IPHONE". Only the first character is converted.
    • Dropping the rest of the word. Without + word.substring(1), "hello" would become "H".
    • Empty words. The lesson promises single spaces, so every piece has a character. With two spaces in a row, "a b".split(" ") gives [a, , b], and substring(0, 1) on the empty piece throws a StringIndexOutOfBoundsException.
    • Forgetting the separator. joinToString() with no argument puts ", " between items, so pass " ".

    Testing

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