Rust Program: Print length of strings
Write a Rust program that iterates over a vector of strings and prints the length of each string.
Sample Solution:
Rust Code:
fn main() {
// Define a vector of strings
let strings = vec!["Rust", "Exercises", "Examples", "Computer Programming"];
// Iterate over each string in the vector
for s in strings.iter() {
// Print the length of each string
println!("Length of '{}' is {}", s, s.len());
}
}
Output:
Length of 'Rust' is 4 Length of 'Exercises' is 9 Length of 'Examples' is 8 Length of 'Computer Programming' is 20
Explanation:
In the exercise above,
- Define a vector 'strings' containing a list of strings.
- Use a "for" loop to iterate over each string in the vector.
- For each string 's', we print its length using the "len()" method.
Rust Code Editor:
Previous: Rust Program: Calculate sum of range of numbers.
Next: Rust Program: Calculate product of Tuple elements.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics