Creating String Slices
Part of the Logic & Flow section of Coddy's Rust journey — lesson 55 of 66.
Now that you understand the difference between String and &str, let's learn how to create string slices from existing strings. There are two main ways to create a &str from a String.
The simplest way is to use the reference operator & with your String. This creates a slice that references the entire string:
let my_string = String::from("Hello World");
let slice: &str = &my_string; // This creates a slice of the entire stringYou can also create slices of specific parts of a string using range syntax. The format is &string[start..end], where start is the beginning index and end is one past the last character you want to include. These indices are of type usize, which is Rust's unsigned integer type used for indexing and sizes — it can only be zero or positive, which makes sense since a string index can never be negative:
let my_string = String::from("Hello World");
let first_word = &my_string[0..5]; // This gives us "Hello"
let second_word = &my_string[6..11]; // This gives us "World"Challenge
EasyYou will receive two inputs. The first input is a full sentence, and the second input is two numbers separated by a space representing the start and end indices for creating a slice. Create a String from the first input, then create a string slice using the range specified by the two indices. Print the original string on the first line and the extracted slice on the second line.
Requirements:
- Read the first input (the full sentence) and trim whitespace
- Create a
Stringfrom this input - Read the second input (two numbers separated by a space) and trim whitespace
- Split the second input by space to get the start and end indices
- Parse both indices to
usize - Create a string slice using the range syntax
&string[start..end] - Print the original string
- Print the extracted slice
Input:
- First line: A sentence (e.g.,
Hello World) - Second line: Two numbers separated by a space (e.g.,
0 5)
Output:
- First line: The original string
- Second line: The extracted slice
Cheat sheet
There are two main ways to create a &str from a String.
Use the reference operator & to create a slice of the entire string:
let my_string = String::from("Hello World");
let slice: &str = &my_string;Use range syntax &string[start..end] to create slices of specific parts:
let my_string = String::from("Hello World");
let first_word = &my_string[0..5]; // "Hello"
let second_word = &my_string[6..11]; // "World"The start index is inclusive and the end index is exclusive (one past the last character).
Try it yourself
use std::io;
fn main() {
// Read the first input (the full sentence)
let mut sentence = String::new();
io::stdin().read_line(&mut sentence).expect("Failed to read line");
let sentence = sentence.trim();
// Read the second input (two numbers separated by a space)
let mut indices = String::new();
io::stdin().read_line(&mut indices).expect("Failed to read line");
let indices = indices.trim();
// TODO: Write your code below
// Parse the indices and create the string slice
// Print the original string and the slice
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together6Handling Absence with 'Option'
What is an 'Option'?Using 'match' with 'Option'is_some() and is_none()Unwrapping an 'Option'The expectProviding a Default: unwrap_orRecap - Find an Element9String Slices and More
String vs. &strCreating String SlicesSlices as Function ParametersOther SlicesRecap - Find First Word