w3resource

Rust Program: Convert strings to Uppercase

Rust Iterators and Iterator Adapters: Exercise-10 with Solution

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/functional-programming/rust-iteretors-and-iterator-adapters-exercise-10.php