Start learning free

LESSON 222 OF 292 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Capitalize Each Word in Swift: split, prefix and joined

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

    SWIFT · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Capitalize Each Word in Swift, 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 doesn't start or end with a space. Only the first character of each word changes: the rest stays exactly as it is, even if it has capital letters. A first character with no upper case, such as a digit, stays too.

    "hello world" becomes "Hello World". "iPhone and NASA" becomes "IPhone And NASA": "Phone" and "ASA" keep their letters as they were. "3d printing" becomes "3d Printing".

    Approach

    Break the sentence into words, fix the first character of each word, and glue the words back together with spaces. That gives three small jobs, each of which has a standard Swift tool: split to cut, prefix and dropFirst to take a word apart, and joined to put the pieces together.

    Because the words are separated by single spaces, splitting at a space and joining with a space puts every space back where it was.

    Step by step

    1. Split the sentence. sentence.split(separator: " ") returns the words. Each piece is a Substring, a view into the original string, and the whole result is an Array<Substring>.
    2. Create var result = [String](), an empty array of strings. It grows inside the loop, so it is a var.
    3. Loop over the words with for word in words.
    4. Build the capitalized word. word.prefix(1) is the first character, .uppercased() turns it into an upper-case String, and String(word.dropFirst()) is everything after it, converted from a Substring to a String. Adding the two strings gives the new word. A one-letter word works too: dropFirst() of it is empty.
    5. Append it to result.
    6. Join and return. result.joined(separator: " ") glues the strings together with a space between each two.

    The solution in Swift

    class Solution {
        func capitalizeWords(_ sentence: String) -> String {
            let words = sentence.split(separator: " ")
            var result = [String]()
            for word in words {
                let capitalized = word.prefix(1).uppercased() + String(word.dropFirst())
                result.append(capitalized)
            }
            return result.joined(separator: " ")
        }
    }
    

    Swift details worth knowing:

    • Substring versus String. split gives Substring values. prefix(1).uppercased() already returns a String, but word.dropFirst() is still a Substring, and + needs two values of the same type. Wrapping it in String(...) fixes that.
    • prefix(1) is safe. It takes at most one character and doesn't fail on an empty string. Indexing with word[0] isn't possible: Swift strings can't be indexed with an Int.
    • uppercased() on a digit. Upper-casing "3" returns "3", so words starting with a digit need no special case.
    • split drops empty pieces. By default it leaves out empty subsequences. With the lesson's single spaces that makes no difference, but it means doubled spaces would collapse into one when joined back.
    • let and var. words and capitalized never change, so they are let. result grows, so it is var.

    Edge cases and common mistakes

    • One word. "hello" gives "Hello", and the join adds no space.
    • One-letter words. "a b" gives "A B".
    • Apostrophes. "it's ok" gives "It's Ok". Only the first character of "it's" changes.
    • Existing capitals. "learn to code with AlgoCademy" gives "Learn To Code With AlgoCademy". Lower-casing the rest of each word would damage "NASA", which the lesson says to leave alone.
    • Forgetting the String(...) conversion. Adding a String and a Substring doesn't compile.

    Testing

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