Start learning free

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

Capitalize Each Word in Go: Split, ToUpper and Join

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

    GO · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Capitalize Each Word in Go, explained

    Problem overview

    The function capitalizeWords receives 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 doesn't start or end with a space. Only the first character of each word changes: the rest stays exactly as it is, upper-case letters included. A first character with no upper case, like a digit, stays as it is.

    "hello world" becomes "Hello World". "learn to code with AlgoCademy" becomes "Learn To Code With AlgoCademy". "iPhone and NASA" becomes "IPhone And NASA": only the first character of each word is touched, so Phone and ASA keep their cases.

    Approach

    Break the sentence into words, fix each word, and glue the words back together. The strings package has the two ends of that pipeline:

    • strings.Split(sentence, " ") returns a slice of the pieces between spaces.
    • strings.Join(result, " ") puts a slice of strings back together with a space between each two.

    Because the words are separated by single spaces, splitting and joining at " " restores every space in its place. In the middle, strings.ToUpper turns a string into upper case. Applied to just the first character of a word, it changes nothing else.

    Step by step

    1. Split the sentence into a slice named words with strings.Split(sentence, " ").
    2. Create result as an empty slice of strings, []string{}. It collects the fixed words in order.
    3. Loop over words with range, with _ for the index and word for the word.
    4. Build capitalized: the first character, word[0:1], in upper case with strings.ToUpper, followed by the rest of the word, word[1:]. For a one-letter word the rest is empty, so it still works.
    5. Add it to result with append, and store what append returns back in result.
    6. Join and return: strings.Join(result, " ").

    The solution in Go

    func capitalizeWords(sentence string) string {
        words := strings.Split(sentence, " ")
        result := []string{}
        for _, word := range words {
            capitalized := strings.ToUpper(word[0:1]) + word[1:]
            result = append(result, capitalized)
        }
        return strings.Join(result, " ")
    }
    

    Go details:

    • Slicing a string gives a string. word[0:1] is a one-byte string, not a byte, so it can go straight into strings.ToUpper. The expression word[0] would be a byte, which ToUpper doesn't accept. Likewise word[1:] is everything from index 1 on, and it is empty, not an error, for a one-letter word.
    • Bytes, not characters. String indexes count bytes. That is fine for English letters, digits and apostrophes, which take one byte each, as the lesson's inputs do. A first character that takes two bytes, such as é, would be cut in half, and strings.ToUpper would return the broken byte as the replacement character.
    • append returns the slice. Without result = the new word is lost.
    • Digits and apostrophes. strings.ToUpper("3") is "3", so a word like 3d becomes 3d unchanged, and the next word is handled separately.

    Complexity

    Splitting, the loop and joining each walk the sentence once, so the time is proportional to its length. The space is also proportional to the length, for the slices of words and the new string.

    Edge cases and common mistakes

    • One word. "a" gives "A", and a sentence of one word works like any other.
    • Letters after the first. Don't upper-case the whole word: "iPhone and NASA" must keep Phone and ASA as they are.
    • Digit first. "3d printing" gives "3d Printing".
    • Double spaces. The lesson guarantees single spaces. With two in a row, Split produces an empty word between them, and word[0:1] on an empty string stops the program with a "slice bounds out of range" panic. Check len(word) first if you reuse this code on other input.

    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".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free