Start learning free

LESSON 217 OF 667 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Capitalize Each Word in C++: istringstream and toupper

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 7
    Ctrl + Enter to check

    C++ · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Capitalize Each Word in C++, 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 of the word stays exactly as it is, even when it contains upper-case letters, and a first character with no upper case, such as a digit, stays as it is.

    For "hello world" the answer is "Hello World". For "learn to code with AlgoCademy" it is "Learn To Code With AlgoCademy", because AlgoCademy already starts with a capital. For "iPhone and NASA" it is "IPhone And NASA": the Phone part and the ASA part are left alone.

    Approach

    The task has three parts: cut the sentence into words, change each word's first character, and join the words back with single spaces. C++ strings have no split method, so the lesson uses a stream. An istringstream wraps a string and lets you read from it the way cin reads input. The extraction operator >> reads the next word, skipping any spaces before it. When no words are left, the expression words >> word becomes false, which makes it a natural loop condition.

    Inside the loop, word[0] is the first character of the current word, and toupper turns a letter into its upper-case form. It leaves digits and punctuation alone. Strings are mutable in C++, so the character can be replaced in place while the rest of the word stays untouched.

    The joining step puts a space before every word except the first. It tests whether result is still empty: it is empty only before the first word has been added.

    Step by step

    1. Create the stream. Build an istringstream named words from sentence.
    2. Create result. It is a string that starts empty and will hold the finished sentence.
    3. Read the words. Declare a string named word, then loop with while (words >> word). Each pass has the next word in word.
    4. Capitalize it. Assign toupper(word[0]) back to word[0].
    5. Add the separator. If result isn't empty, append a space first.
    6. Append the word to result with +=.
    7. Return result after the loop. It has every word capitalized, with single spaces between them.

    The solution in C++

    class Solution {
    public:
        string capitalizeWords(string sentence) {
            istringstream words(sentence);
            string result = "";
            string word;
            while (words >> word) {
                word[0] = toupper(word[0]);
                if (result != "") {
                    result += " ";
                }
                result += word;
            }
            return result;
        }
    };
    

    Details worth knowing:

    • word[0] is always valid here. The extraction operator only succeeds when it reads at least one character, so word is never empty inside the loop. On an empty string, word[0] would be the terminating null character, which is not something to modify.
    • toupper works on single characters. It takes an int and returns an int, and assigning the result to word[0] converts it back to char. For the lesson's letters, digits and apostrophes this is exact. It handles plain ASCII letters. Text in other alphabets needs different tools.
    • Where the whitespace goes. >> skips every whitespace character before a word, so the output always has exactly one space between words. With the input "a b", which has two spaces, the function returns "A B". The lesson's input has single spaces, so the output spacing matches the input exactly.
    • The header. istringstream is declared in the <sstream> header, which a program of your own has to include.
    • Testing for an empty string. result != "" compares the string with an empty literal. !result.empty() means the same and is the more common spelling, but either works here.
    • Building the string. result += word appends in place, which is cheaper than result = result + word, which creates a temporary string.

    Complexity

    Time: O(n), where n is the length of the sentence. Each character is read once by the stream and copied once into result. Space: O(n) for the stream, the current word and the result.

    Edge cases and common mistakes

    • A single word. The sentence has at least one word, so the result is never empty. The loop runs once, and no space is added because result is still empty. "7up rocks" becomes "7up Rocks": the 7 has no upper-case form and stays.
    • Words with capitals inside. "iPhone and NASA" gives "IPhone And NASA". Don't convert the whole word to lower case first, because that would change NASA to Nasa.
    • Apostrophes. "it's ok" gives "It's Ok". The letter after the apostrophe isn't a word start, because the word is only split at spaces.
    • A trailing space. Adding a space after every word, rather than before every word but the first, would leave an extra space at the end of the result.
    • Forgetting to assign. Calling toupper(word[0]) without assigning the result changes nothing, because the function returns the upper-case character and does not modify its argument.

    Testing

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