Rust Fundamentals · 20 XP Pro

String slices

A String owns its text on the heap. A string slice, &str, is a borrowed view into text that lives somewhere else. String literals like "hi" are &str too.

Slice with byte ranges, just like arrays:

let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..];

Ranges are in bytes and must fall on character boundaries, so for plain ASCII text they are safe. char_indices() gives you each character together with its byte position, which is handy for finding where to cut.

Prefer &str for function parameters: a &String converts to &str automatically, so one function accepts both owned strings and literals. Return String only when you must build new text.

Your task

Write two pub functions:

  • first_word(text: &str) -> &str returns the part of text before the first space character (' '), or all of text if it has no space. Return a slice of the input, not a new String.
  • shout(raw: &str) -> String trims whitespace from both ends, converts the rest to uppercase, and returns it as an owned String. The trim() and to_uppercase() methods will help.

Next lesson →

Sign in to run your code. It's free.