Title Case Each Word With Char Methods

Build a title-case converter from split_whitespace and char methods, uppercasing the first character of each word while lowercasing the rest.

RustCli Tooling

Code

rustsnippet
21 lines
fn title_case(input: &str) -> String {
    let mut words = Vec::new();
    for word in input.split_whitespace() {
        let mut chars = word.chars();
        let first = chars.next().unwrap_or(' ');
        // char::to_uppercase 可能产出多个字符(如 ß -> SS),用 flat_map 展开
        let head: String = first.to_uppercase().collect();
        let tail: String = chars.flat_map(|c| c.to_lowercase()).collect();
        words.push(format!("{head}{tail}"));
    }
    words.join(" ")
}

fn main() {
    println!("{}", title_case("deploy the api gateway"));
    println!("{}", title_case("  ORDER   STATE  "));
    println!("{}", title_case("ßeta version"));

    // 空输入只产生零个词,join 得到空串
    println!("empty: {:?}", title_case("   "));
}

Inside the snippet

Structurally, expect the functions title_case and main and nothing else.

The loop for word in input.split_whitespace() is the only repeated construct.

Putting it to use

Signature: fn title_case(input: &str) -> String

The demo output is labeled (empty:), which makes each printed line traceable to the operation that emitted it.

main sequences title_case; executing the file runs that flow once.

Core lines

let tail: String = chars.flat_map(|c| c.to_lowercase()).collect();
let head: String = first.to_uppercase().collect();
let first = chars.next().unwrap_or(' ');

Interactive Tools for This Topic

FAQ

What does Title Case Each Word With Char Methods print when run?
No setup needed: run the file and look for labeled lines like `empty:` in the output.