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
:
-
first_word(s: &str) -> &str
Return the substring up to the first space. If there is no space, return the whole string. -
last_n(s: &str, n: usize) -> &str
Return the lastn
characters ofs
. Ifn
exceeds the length, returns
.
(Assume ASCII so that byte and character counts match.)
💡 Hints
- For
first_word
, scan bytes and stop atb' '
to find the split index. - For
last_n
, clampn
withn.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");