Capitalize (and Title Case) Words In Rust
Introduction
There's no built-in method to capitalize strings in Rust. The .to_uppercase()
and .to_lowercase()
methods are available1, but nothing to make only the first letter uppercase.
Most of the time, I'm looking to change a string to Title Case. That is, don't just capitalize the first word but adjust all the words accordingly. I'm using the titlecase2 crate for the functionality:
---
[dependencies]
titlecase = "3.5.0"
---
use titlecase::Titlecase;
fn main() {
let source = "alfa bravo of charlie";
let updated = source.titlecase();
println!("{}", updated);
}
Alfa Bravo of Charlie
Notice that the of
didn't get uppercased. That's because there are some rules built into the crate that prevent "small words" from being capitalized3.
Capitalize Everything
If you really do need to capitalize everything the capitalize
4 crate is available as well.
It only capitalizes the first word in a string. If you need to do everything you have to do something like splitting on whitespace then running the .capitalize()
method on each word independently.
I'll write that up if I ever run into a case where I need it instead of titlecase
.
Footnotes
Details the rules for when letters are made upper and lower case.
The original style guide the titlecase create is based off of from Daring Fireball.