Strings and Slices
Level: intro (score: 1)
π These intro exercises are prep for our
Rust Intro Cohort Program.
π― 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. &strslices 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 lastncharacters ofs. Ifnexceeds 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, clampnwithn.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");
pub fn first_word(s: &str) -> &str {
// TODO: Return substring up to the first space or whole string if none
}
pub fn last_n(s: &str, n: usize) -> &str {
// TODO: Return last n characters of s (clamp n to length)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_first_word() {
assert_eq!(first_word("hello world"), "hello");
assert_eq!(first_word("rustacean"), "rustacean");
}
#[test]
fn test_last_n() {
assert_eq!(last_n("abcdef", 3), "def");
assert_eq!(last_n("hi", 5), "hi");
}
}