A Rust command-line utility that extracts the first and second words from a given string input. The project serves as both a functional word extraction utility and an educational example of Rust's ownership and borrowing system, with detailed comments explaining the algorithms and memory management principles.
- Extracts the first word from a string
- Extracts the second word from a string
- Handles edge cases like empty strings and single-word inputs
- Memory efficient using string slices
The first_word function extracts the first word from a string using the following approach:
- Converts the input string to bytes for efficient iteration
- Iterates through each byte in the string
- Returns the substring from the start up to (but not including) the first space character
- If no space is found, returns the entire string as it's considered a single word
The second_word function extracts the second word using this approach:
- Tracks word boundaries using start and end indices
- Iterates through the string to find the second word
- Identifies the second word as the sequence of characters between the first and second spaces
- Handles edge cases where the input might have fewer than two words
- mise - A version manager for multiple languages and tools
-
Clone the repository
git clone https://github.com/Brisinger/first_word.git cd first_word -
Install Rust and tools using mise:
mise install
This will install:
- Rust 1.85.0
- rustfmt (for code formatting)
- clippy (for linting)
To build the project with optimizations:
mise run buildTo run the optimized release build:
cargo run --release- Format code:
mise run format - Check for errors:
mise run check - Run linter:
mise run lint - Run all CI checks:
mise run ci
- Run the program:
cargo run --release - Enter a sentence when prompted
- The program will display the first and second words
$ cargo run
Compiling first_word v0.1.0 (/path/to/first_word)
Finished dev [unoptimized + debuginfo] target(s) in 0.50s
Running `target/debug/first_word`
Please enter a sentence: Hello World from Rust
First word: Hello
Second word: WorldThis project is licensed under the MIT License - see the LICENSE file for details.
Author: Shubhojit Dasgupta