Rust Program: Convert strings to Uppercase
Write a Rust program that iterates over a vector of strings and converts each string to uppercase.
Sample Solution:
Rust Code:
fn main() {
let strings = vec!["rust".to_string(), "exercises".to_string()]; // Define a vector of strings
println!("Original strings: {:?}", strings); // Print the original vector of strings
let uppercased_strings: Vec<String> = strings // Iterate over each string in the vector
.into_iter() // Convert the vector into an iterator
.map(|s| s.to_uppercase()) // Apply the to_uppercase method to each string to convert it to uppercase
.collect(); // Collect the modified strings into a new vector
println!("Uppercased strings: {:?}", uppercased_strings); // Print the vector of strings converted to uppercase
}
Output:
Original strings: ["rust", "exercises"] Uppercased strings: ["RUST", "EXERCISES"]
Explanation:
The above Rust program iterates over a vector of strings, converts each string to uppercase using the "to_uppercase()" method, and collects the modified strings into a new vector. It then prints both the original vector of strings and the vector of strings converted to uppercase.
Rust Code Editor:
Previous: Rust Program: Filter Odd numbers.
Next: Rust Program: Cube Vector 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