Problem overview
The function capitalize_words receives a sentence and returns it with the first letter of every word in upper case. Words are separated by single spaces, and the sentence has no space at either end. Only the first character of a word changes: the rest stays exactly as it was, even when it holds capitals. A first character with no upper case, such as a digit, stays as it is.
"hello world" becomes "Hello World". "iPhone and NASA" becomes "IPhone And NASA": the "Phone" and "ASA" parts are left alone.
Approach
Break the sentence into words, fix each word, and put the words back together. The three jobs map onto three standard tools: split_whitespace() to split, a loop to build the new words, and join(" ") to glue them.
For one word, the fix is "upper-case the first character, then append everything after it". The rest is copied untouched, which is what keeps "NASA" and "Phone" as they are.
Step by step
- Split into words.
sentence.split_whitespace().collect()gives aVec<&str>, where each item borrows a piece of the original sentence. - Create an empty
result. It is a mutableVec<String>, made withVec::new(), and it will hold the new words in the same order. - Loop over the words. Each
wordis a&str. - Build
capitalized. Take the sliceword[0..1], the first character, make it upper case withto_uppercase(), then append&word[1..], the rest of the word. - Push it onto
result. - Join the words with
result.join(" ")as the last expression. One space between each two words puts every space back where it was.
The solution in Rust
impl Solution {
fn capitalize_words(sentence: String) -> String {
let words: Vec<&str> = sentence.split_whitespace().collect();
let mut result: Vec<String> = Vec::new();
for word in words {
let capitalized = word[0..1].to_uppercase() + &word[1..];
result.push(capitalized);
}
result.join(" ")
}
}
- Slices by byte range.
word[0..1]is the first byte, as a&str. For the English letters, digits and apostrophes this lesson uses, one byte is one character. Slicing is by bytes, not characters, so a word that starts with a multi-byte character such aséwould panic with the message "byte index 1 is not a char boundary". to_uppercase()returns a newString. It can't change the slice in place, since a&stris read-only. For a digit such as"3"it returns"3"unchanged.String + &str. The+operator takes the leftStringby value and appends a&strto it. That is why the right side is written&word[1..], a borrowed slice, and why the left side must be aString.joinon a vector ofString. It builds oneStringwith the separator between neighbours and nothing at the ends.- Looping over
words. Theforloop consumes the vector. That is fine, because it isn't needed afterwards.
Edge cases and common mistakes
- One word or one letter.
"a"gives"A". The sliceword[1..]is then empty, which is allowed. - Digit first.
"3 little pigs"gives"3 Little Pigs": the 3 has no upper case, and the next words are capitalized as usual. - Apostrophes.
"don't stop"gives"Don't Stop". Nothing after the first character changes, so thetafter the apostrophe stays lower case. - Lowering the rest. Don't convert the whole word to lower case:
"NASA"must stay"NASA". - Splitting on a space.
split(' ')andsplit_whitespace()agree on single spaces. With two spaces in a row,"a b".split(' ')yields an empty piece between them, and slicing that empty word would panic.split_whitespace()skips such pieces.
Testing
"hello world"gives"Hello World"."learn to code with AlgoCademy"gives"Learn To Code With AlgoCademy"."iPhone and NASA"gives"IPhone And NASA"."3 little pigs"gives"3 Little Pigs"."don't stop"gives"Don't Stop"."a"gives"A".
