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.
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.
for
-loop to iterate over these values.string
up to the point where zero further words are required. We use unwrap
on a substring.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
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.
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.