str::to_ascii_uppercase¶
Level: reference · for working programmers
One line: A new String with a–z uppercased and everything else untouched — length-preserving, unlike to_uppercase.
Stable since 1.23.0.
The mirror of to_ascii_lowercase, and it avoids the ß → SS expansion entirely by simply not touching ß.
That makes it round-trippable within ASCII: to_ascii_uppercase().to_ascii_lowercase() returns the original for any ASCII input, which the Unicode pair does not guarantee.
Use it for protocol tokens, hex digits, and anything specified in ASCII. Use to_uppercase for text a person will read.
Example¶
str_to_ascii_uppercase.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
println!("{:?}", "hello".to_ascii_uppercase());
// ß is left alone, so no expansion.
println!("{:?} vs {:?}", "straße".to_ascii_uppercase(), "straße".to_uppercase());
// Round-trips within ASCII.
let s = "MiXeD case 123!";
println!("{}", s.to_ascii_uppercase().to_ascii_lowercase() == s.to_ascii_lowercase());
// Length is always preserved.
for s in ["ß", "fi", "abc"] {
println!("{:<5} ascii {} bytes, unicode {} bytes",
format!("{s:?}"), s.to_ascii_uppercase().len(), s.to_uppercase().len());
}
// Hex digits: an ASCII-by-definition alphabet.
println!("{:?}", "1f4a9".to_ascii_uppercase());
}
Verified output of str_to_ascii_uppercase.rs — regenerated by tools/run_examples.py, never hand-typed.
"HELLO"
"STRAßE" vs "STRASSE"
true
"ß" ascii 2 bytes, unicode 2 bytes
"fi" ascii 3 bytes, unicode 2 bytes
"abc" ascii 3 bytes, unicode 3 bytes
"1F4A9"
See also¶
str::to_ascii_lowercase— the other directionstr::to_uppercase— the Unicode-aware versionstr::make_ascii_uppercase— the same edit, in placestr::is_ascii— checking the assumption
str::to_ascii_uppercase in the standard library ↗
Po polsku¶
W drugą stronę pułapka wygląda inaczej niż przy to_ascii_lowercase: unikodowe to_uppercase potrafi łańcuch znaków wydłużyć ("straße" → "STRASSE", ligatura "fi" → "FI"), a wersja ASCII po prostu tych znaków nie dotyka, więc wychodzi "STRAßE" i dokładnie tyle samo bajtów, ile było na wejściu. Stąd bierze się jedyna gwarancja obiegu w obie strony, jaką da się tu w ogóle uzyskać: dla wejścia czysto ASCII to_ascii_uppercase().to_ascii_lowercase() odtwarza oryginał, czego para unikodowa nie obiecuje. Praktyczny podział jest więc prosty — cyfry szesnastkowe, tokeny protokołów i wszystko, co jest ASCII z definicji ("1f4a9" → "1F4A9"), a do tekstu czytanego przez człowieka to_uppercase, bo "gdańsk".to_ascii_uppercase() daje "GDAńSK".
Szukaj po polsku: zamiana na wielkie litery · niezmienna długość łańcucha · rust to_ascii_uppercase · rust uppercase ß SS expansion