Problem overview
The function concat_first_and_last_char takes a String named s and returns a new String with two characters: the first character of s, then its last one. The input has at least two characters, so both always exist.
For "hello" the answer is "ho". For "Hello World!" it is "H!": every character counts, so the last one is the exclamation mark, and the capital H stays a capital. For "ab" the first and last characters are the two characters of the string, so the answer is "ab" again.
Approach
Many languages let you write s[0] to get the first character. Rust doesn't allow a string to be indexed by a single number. A String is stored as UTF-8 bytes, and one character can take more than one byte, so "the item at position 0" is not a well-defined thing to ask for. What Rust does allow is a range: &s[0..1] borrows the bytes from position 0 up to, but not including, position 1, as a &str. That is a one-character piece of text, which is exactly what the function needs.
The last character is a slice too, but its start depends on the length: s.len() - 1 is the position of the last byte, and a range with no end, such as s.len() - 1.., runs to the end of the string.
Step by step
- Borrow the first character with the range
0..1. The result is a&strof length one. - Borrow the last character with a range that starts at
s.len() - 1and has no end. - Glue the two pieces together with
format!. It works likeprintln!, with one{}for each value, but it returns a newStringinstead of printing. - Return the result.
The solution in Rust
impl Solution {
fn concat_first_and_last_char(s: String) -> String {
return format!("{}{}", &s[0..1], &s[s.len() - 1..]);
}
}
Some details worth knowing:
- Ranges stop before their end.
0..1holds only position 0. Writing0..2would give two characters. &borrows. A slice of aStringis a&strthat points intos, so nothing is copied untilformat!builds the result.- The range
s.len() - 1..parses as(s.len() - 1)... The subtraction happens first. returnis optional at the end. The lesson writes it explicitly; without it and without the semicolon, the last expression would be returned.
Edge cases and common mistakes
- Two characters. With
"ab"the two slices are"a"and"b", and the result is"ab". - Slices count bytes, not characters. For the English letters, digits and punctuation in this lesson, one character is one byte, so byte positions and character positions agree. A character like
étakes two bytes, and"é".len()is 2. Slicing in the middle of such a character panics with the message "byte index 1 is not a char boundary". To handle any text, uses.chars().next()ands.chars().last(), which return characters as anOption<char>. - Using
s.len()as the start. The ranges.len()..is empty, so the last character would be missing. The start has to be one less than the length. - An empty string. The lesson guarantees at least two characters. With an empty string,
s.len() - 1would be ausizesubtraction below zero, which panics in a debug build and wraps around in an optimized build, and either way the slice would fail.
Testing
"hello"gives"ho"."Hello World!"gives"H!"."ab"gives"ab".
