Problem overview
The function stutterize takes a String named word and returns it said with a stutter: its first two characters, a hyphen, then the whole word. The word has at least 2 letters, all English letters.
For "dog" the result is "do-dog". For "Hello" it is "He-Hello", with the capital H in both places, because nothing changes the case. For "ab" the first two characters are the whole word, so the result is "ab-ab".
Approach
The result is built from three pieces: a two-letter slice, a fixed hyphen and the original word. format! fits this exactly. It takes a template such as "{}-{}" and fills each {} with a value, in order, returning a new String. The hyphen lives in the template; the two values are the slice and the word.
For "Hello" the slice &word[0..2] is "He", which is 2 bytes long, so the template produces "He-Hello". A hand-built version would create an empty String and push the pieces one by one; the template does the same work in one expression and reads like the result it produces.
Step by step
- Write the template with a hyphen between two
{}. - Fill the first
{}with the first two characters:&word[0..2]. The range stops right before 2, so it keeps positions 0 and 1. - Fill the second
{}withworditself. - Return the string that
format!built.
The solution in Rust
impl Solution {
fn stutterize(word: String) -> String {
return format!("{}-{}", &word[0..2], word);
}
}
Some details worth knowing:
format!doesn't take ownership. It only reads its arguments, sowordcan be used right after the slice borrowed from it in the same call.- The slice is a
&str.&word[0..2]points intoword. Without the&, Rust would complain that the size of the slice isn't known at compile time. - The
&is required. Writingword[0..2]without it insideformat!fails to compile with "the size for values of typestrcannot be known at compilation time". The slice has to be borrowed. - Bytes, not characters. Ranges on a string count bytes. English letters are one byte each, so
0..2is two letters. A word starting with a two-byte character such aséwould make0..2cover just that one letter, and a word like"aé"would panic because the range ends in the middle of a character.
Edge cases and common mistakes
- A two-letter word.
&word[0..2]is the whole word, giving"ab-ab". - Range end off by one.
0..1gives one letter,0..3three:"dog-dog"for the first example. - Forgetting the hyphen or putting it in the wrong place, such as
"{}{}-". - Changing the case. Don't call
to_lowercase: the stutter keeps the capital in"He-Hello". - A one-letter word. It would make the range
0..2run past the end and panic. The lesson guarantees at least 2 letters.
Testing
Try these inputs in the editor above.
"dog"gives"do-dog"."Hello"gives"He-Hello"."ab"gives"ab-ab".
