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
- Create the stream. Build an
istringstreamnamedwordsfromsentence. - Create
result. It is astringthat starts empty and will hold the finished sentence. - Read the words. Declare a
stringnamedword, then loop withwhile (words >> word). Each pass has the next word inword. - Capitalize it. Assign
toupper(word[0])back toword[0]. - Add the separator. If
resultisn't empty, append a space first. - Append the word to
resultwith+=. - Return
resultafter 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, sowordis never empty inside the loop. On an empty string,word[0]would be the terminating null character, which is not something to modify.toupperworks on single characters. It takes anintand returns anint, and assigning the result toword[0]converts it back tochar. 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.
istringstreamis 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 += wordappends in place, which is cheaper thanresult = 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
resultis 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 changeNASAtoNasa. - 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".
