Problem overview
The function amazing_to_not_amazing takes a word s that starts with a lowercase a and returns "not ", with its space, followed by s without its first character. That is how "amazing" becomes "not mazing".
For "amazing" the result is "not mazing". For "aMAZING" it is "not MAZING": only the first character goes away, and the others keep their case. For "an" it is "not n".
Approach
The task has two parts: a fixed prefix and the word minus its first character. The second part is a slice. In Rust, &s[1..] borrows the part of s from byte 1 to the end of the string. A range with no end means "up to the end", so the slice keeps every character except the first one.
To put the prefix and the slice together, format! is the simplest tool. It builds a new String from a template, where each {} is replaced by a value.
A tempting alternative is to build the result by hand: start a String, push "not " onto it, then push the rest of the word. That works, but it takes several statements for what a template says in one line. The template also shows the shape of the answer: the text around the {} is what stays fixed, and the {} is the part that depends on the input.
Here is how the slice behaves on its own. For t = "amazing", &t[1..] is "mazing": position 0, the a, is skipped and everything after it is kept.
Step by step
- Take the slice from index 1 to the end. Index 0 is the
athat has to disappear. - Write the template
"not {}", with the space inside it before the{}. Without the space, "amazing" would become "notmazing". - Return the formatted string.
The solution in Rust
impl Solution {
fn amazing_to_not_amazing(s: String) -> String {
return format!("not {}", &s[1..]);
}
}
Some details worth knowing:
- The slice is a borrow.
&s[1..]has the type&strand points intos. No text is copied untilformat!builds the new string. - Byte positions. A slice range counts bytes. Here every character is an English letter, which is one byte, so skipping one byte skips one character.
- The first character is dropped, not checked. The function doesn't test that the word really starts with
a. The lesson guarantees it, so any first letter would be removed the same way.
Edge cases and common mistakes
- Forgetting the space.
"not{}"gives"notmazing". - Starting the range at 0.
&s[0..]is the whole word, so theastays and the result is"not amazing". - Changing the case. Nothing here needs
to_uppercaseorto_lowercase:"aMAZING"keeps its capitals. - Two-letter words. For
"an"the slice&s[1..]is"n", so the result is"not n". - Non-English letters. Slicing at byte 1 of a word that starts with a multi-byte character panics. The lesson's words start with
a, a single byte, so this can't happen here.
Testing
"amazing"gives"not mazing"."aMAZING"gives"not MAZING"."an"gives"not n".
