Home
Rust
String First Words
Updated Sep 12, 2023
Dot Net Perls
First words. It is sometimes helpful to get a string containing the first words from another string. This can be accomplished in Rust with a for-loop over chars.
With the chars iterator, we access each char in a string in order. And with enumerate() we can get each char and its index. We can count the spaces in this way.
Example. Consider the first_words() example function. This function receives a source str reference, and a count of words (as an isize) we want to keep.
Step 1 We call the enumerate function over the chars iterator. We use a for-loop to iterate over these values.
iter
Loop, String Chars
Step 2 When each space is encountered, we reduce the word count required. This is how we count words.
Step 3 We return a new string up to the point where zero further words are required. We use unwrap on a substring.
Substring
Step 4 If we do not have enough words in the source string to keep, we just return the entire string.
fn first_words(source: &str, mut count: isize) -> String { // Step 1: use enumerate over chars iterator to get indexes and chars. for (i, c) in source.chars().enumerate() { // Step 2: reduce count on space char. if c == ' ' { count -= 1; // Step 3: return new string up to this point when no more words needed. if count == 0 { return source.get(0..i).unwrap().to_string(); } } } // Step 4: just return entire string. source.to_string() } fn main() { let value = "there are many reasons"; // Test our first words method. let result1 = first_words(value, 2); println!("[{result1}]"); let result2 = first_words(value, 3); println!("{result2}"); let result3 = first_words(value, 100); println!("{result3}"); }
[there are] there are many there are many reasons
Performance notes. The function first_words will allocate and copy the initial words into a string. It would be possible to use indexes to avoid this copy if needed.
Summary. Simple string-processing functions can be written in safe Rust code. And with the safety in Rust, we can be assured the code will not cause any future memory-related issues.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 12, 2023 (new).
Home
Changes
© 2007-2025 Sam Allen