Rust Changing Case
Case conversion changes text to upper case or lower case. to_uppercase and to_lowercase each build a new String.
The two case builders
Each returns a new String in the other case:
println!("{}", "rust".to_uppercase());
println!("{}", "RuSt".to_lowercase());Case can change the length
The German ß has no single capital letter, so its uppercase is two letters: SS. Six letters go in, seven come out:
println!("{}", "ß".to_uppercase());
println!("{} -> {} ({} chars)", "straße", "straße".to_uppercase(), "straße".to_uppercase().chars().count());The ASCII-only twins
to_ascii_uppercase leaves ß alone, because ß is not an ASCII letter. Same text, two honest answers:
println!("{}", "straße".to_ascii_uppercase());Compare without building
eq_ignore_ascii_case answers the question directly — no new String on either side:
println!("{}", "ReadMe.MD".eq_ignore_ascii_case("readme.md"));
println!("{}", "ReadMe.MD" == "readme.md");Example
fn main() {
let word = "straße";
println!("upper = {} ({} chars)", word.to_uppercase(), word.to_uppercase().chars().count());
println!("ascii = {}", word.to_ascii_uppercase());
let answer = "YES";
println!("shouted yes = {}", answer.eq_ignore_ascii_case("yes"));
let quiet = "İ".to_lowercase();
println!("İ lower = {} ({} chars)", quiet, quiet.chars().count());
}Key points
- to_uppercase and to_lowercase build a NEW String.
- The original text is untouched.
- Case is a Unicode idea, not an ASCII one: a letter may become several letters, or the other way round
- to_ascii_uppercase and to_ascii_lowercase touch only the letters A-Z and a-z, and leave every other character exactly as it is
- Comparing case-insensitively by converting both sides allocates two Strings.
- eq_ignore_ascii_case compares directly.
- eq_ignore_ascii_case builds nothing.
In this example, "straße" goes uppercase two ways. to_uppercase gives STRASSE: ß became SS, so 6 letters became 7. to_ascii_uppercase gives STRAßE: only the ASCII letters changed, and ß stayed. Next, a form answer "YES" is compared with eq_ignore_ascii_case and matches "yes" without building any new text. The last line lowercases the Turkish İ. The result looks like an i with a dot. It is really two chars: a plain i plus a combining dot mark. Case in Unicode is a mapping, not a costume change.
Note
eq_ignore_ascii_case ignores case only for ASCII letters.
For full Unicode-insensitive matching, lowercase both sides with to_lowercase and compare those.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Why can to_uppercase change the number of characters in a text?