Recap - Find First Word
Part of the Logic & Flow section of Coddy's Rust journey — lesson 58 of 66.
Challenge
EasyYou will receive a single input containing a sentence with multiple words separated by spaces. Find and print the first word from the sentence using string slicing.
Requirements:
- Read the input sentence and trim whitespace
- Find the position of the first space in the sentence
- Create a string slice from the beginning of the sentence up to (but not including) the first space
- Print the first word
Hint: You can use the .find() method to locate the first space character. Call it like this: sentence.find(' '), passing a space character as the argument. This method returns an Option that contains the index if a space is found. Use .unwrap_or(sentence.len()) to handle cases where there might be no space (single word), defaulting to the full length of the sentence.
Input:
- A sentence with one or more words separated by spaces (e.g.,
Hello World from Rust)
Output:
- The first word from the sentence
Try it yourself
use std::io::{self, BufRead};
fn main() {
// Read input
let stdin = io::stdin();
let sentence = stdin.lock().lines().next().unwrap().unwrap().trim().to_string();
// TODO: Write your code below
// Find the position of the first space
// Create a string slice from the beginning to the first space
// Store the first word in a variable
// Print the first word
// println!("{}", first_word);
}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