Start learning free

LESSON 72 OF 293 · STRINGS - CHALLENGES

Concat First and Last Char in Rust: String Slices

Practice Read the full explanation

Given a string s, return a new string made of two characters: the first character of s, followed by its last character.

 

Example 1:

Input: s = "hello"
Output: "ho"
Explanation: The first character is "h" and the last one is "o".

Example 2:

Input: s = "Hello World!"
Output: "H!"
Explanation: Every character counts, so the last one is the "!", not the "d". The "H" stays upper case.

Example 3:

Input: s = "ab"
Output: "ab"
Explanation: With only two characters, the first is "a" and the last is "b".

 

Constraints:

  • s has at least 2 characters.
  • s contains English letters, digits, spaces and punctuation, and doesn't start or end with a space.
STEP 1 OF 1
    Ctrl + Enter to check

    RUST · STRINGS - CHALLENGES

    Concat First And Last Char in Rust, explained

    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

    1. Borrow the first character with the range 0..1. The result is a &str of length one.
    2. Borrow the last character with a range that starts at s.len() - 1 and has no end.
    3. Glue the two pieces together with format!. It works like println!, with one {} for each value, but it returns a new String instead of printing.
    4. 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..1 holds only position 0. Writing 0..2 would give two characters.
    • & borrows. A slice of a String is a &str that points into s, so nothing is copied until format! builds the result.
    • The range s.len() - 1.. parses as (s.len() - 1)... The subtraction happens first.
    • return is 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, use s.chars().next() and s.chars().last(), which return characters as an Option<char>.
    • Using s.len() as the start. The range s.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() - 1 would be a usize subtraction 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".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free