Rust Program to Capitalize the first character of each word in a String


Capitalize the first character of each word in a String

Rust Programming Language


Capitalize the first character of each word in a String


Problem


To capitalize the first character of each word in a string in Rust, we can split the string into words, capitalize the first character of each word, and then join the words back together.

Here's an example program that demonstrates how to capitalize the first character of each word in a string.

Input


fn main() {
    let s = String::from("the quick brown fox jumps over the lazy dog");

    let capitalized: String = s
        .split_whitespace()
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first_char) => {
                    let capitalized_char = first_char.to_uppercase().next().unwrap();
                    let mut capitalized_word = String::new();
                    capitalized_word.push(capitalized_char);
                    capitalized_word.push_str(chars.as_str());
                    capitalized_word
                }
            }
        })
        .collect::<Vec<String>>()
        .join(" ");

    println!("{}", capitalized);
}{codeBox}


Output


The Quick Brown Fox Jumps Over The Lazy Dog{codeBox}


Explanation


In this program, we create a string object s with the value "the quick brown fox jumps over the lazy dog". We then split the string into words using the split_whitespace() method. We use the map() method to transform each word by capitalizing the first character of the word. To capitalize the first character of the word, we first get an iterator over the characters of the word using the chars() method. We then use a match statement to handle the case where the word is empty. If the word is not empty, we capitalize the first character using the to_uppercase() method and then join it with the rest of the word using the push() and push_str() methods. Finally, we collect the transformed words into a vector and join them back together using the join() method.



Post a Comment