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.
Code
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
Case ConverterConvert text between lowercase, uppercase, title, sentence, camelCase, snake_case, and kebab-case while preserving Unicode letters and numbers.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.