Pybites Logo Rust Platform

Strings and Slices

Level: intro (score: 1)

🎯 In Python, strings are sequences and slicing is easy (s[0:4]).
In Rust, there are two common string types: borrowed &str and owned String.
Slicing &str uses byte indices, so we’ll keep inputs ASCII in this exercise.

Key points for Pythonistas:

  • You can’t index a string by position like s[0] in Rust.
  • &str slices are views into the original data (no allocation).
  • Slices use half‑open ranges: &s[start..end] (end is excluded).

Your task

Implement two functions in src/main.rs:

  1. first_word(s: &str) -> &str
    Return the substring up to the first space. If there is no space, return the whole string.

  2. last_n(s: &str, n: usize) -> &str
    Return the last n characters of s. If n exceeds the length, return s.
    (Assume ASCII so that byte and character counts match.)


💡 Hints

  • For first_word, scan bytes and stop at b' ' to find the split index.
  • For last_n, clamp n with n.min(s.len()) and slice with &s[s.len()-k..].

Example tests:

assert_eq!(first_word("hello world"), "hello");
assert_eq!(first_word("rustacean"), "rustacean");

assert_eq!(last_n("abcdef", 3), "def");
assert_eq!(last_n("hi", 5), "hi");