To get all possible K length substrings of a string in Rust, you can use nested loops to iterate through each possible substring.
In this example,
str
with a value of "Hello World"
.substrings
to store all substrings of length 3.&str[i..j]
and add it to the substrings
vector.substrings
vector.fn main() {
let str = String::from("Hello World");
let k = 3;
let mut substrings: Vec<String> = Vec::new();
for i in 0..=str.len() - k {
for j in i..i + k {
substrings.push(str[i..j + 1].to_string());
}
}
println!("All substrings of length {}: {:?}", k, substrings);
}
All substrings of length 3: ["Hel", "ell", "llo", "lo ", "o W", " Wo", "Wor", "orl", "rld"]
In this tutorial, we learned How to get all the possible K length Substrings in a String in Rust language with well detailed examples.