Problem overview
The function repeat_last_char takes a string s and a number n, and returns a new String made of the last character of s written n times in a row. The string has at least one character, and n is between 1 and 10.
For "banana" and n = 3 the last character is "a", so the result is "aaa". For "Wow!" and n = 2 it is "!!": the last character can be any character. For "z" and n = 1 the string has one character, which is also its last one, so the result is "z".
Approach
There are two jobs: get the last character, then repeat it. Rust can't index a string with a single number, so the last character comes from a slice that starts at s.len() - 1 and runs to the end. Repeating it needs no loop, because string slices have a repeat method: "ab".repeat(3) returns the new String "ababab".
The only subtlety is the type of the count. repeat expects a usize, the type Rust uses for lengths and counts, while the function receives n as an i32. Rust never converts between number types silently, so the call needs n as usize.
Step by step
- Store the last character in
last. Borrow the slice ofsfroms.len() - 1to the end. Leaving out the end of the range means "up to the end of the string", which here is a single character. - Repeat it
ntimes. Callrepeatonlast, passingn as usize, and return the resultingString.
The solution in Rust
impl Solution {
fn repeat_last_char(s: String, n: i32) -> String {
let last = &s[s.len() - 1..];
return last.repeat(n as usize);
}
}
Some details worth knowing:
lastis a&str. It borrows fromsand copies nothing.repeatis the call that allocates a newString.asconverts numbers.n as usizeturns thei32into ausize. For a value from 1 to 10 the conversion is exact. A negativei32would not be:asdoesn't check the sign, so the value would become a hugeusizeand the call would fail. The lesson keepsnpositive.- A count of 0.
"a".repeat(0)is the empty string, son = 0would be fine if the lesson allowed it. - Bytes, not characters. The slice starts at a byte position. For the English letters, digits and punctuation here, that is the same as a character position. If the last character took several bytes, such as
é, starting one byte before the end would cut it in half and panic.
Edge cases and common mistakes
- One-character strings. For
"z",s.len() - 1is 0, so the slice is the whole string. This works because the string isn't empty. - Taking the first character instead of the last. Using
&s[0..1]gives"bbb"for"banana". - Starting at
s.len(). The slices.len()..is empty, so the result would be an empty string. - Passing
ndirectly.last.repeat(n)doesn't compile, becausenis ani32where ausizeis required. - Empty strings. The lesson guarantees at least one character. For an empty string,
s.len() - 1would subtract from zero in ausize.
Testing
"banana",3gives"aaa"."Wow!",2gives"!!"."z",1gives"z".
