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.
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