Skip to content

str::to_ascii_lowercase

str methods · Strings

Level: reference · for working programmers

One line: A new String with AZ lowercased and every other byte left alone — length-preserving, and blind to accents.

pub fn to_ascii_lowercase(&self) -> String

Stable since 1.23.0.

Only the 26 ASCII letters are touched. É comes back as É, unchanged. That is a feature when you are normalizing identifiers, HTTP headers or file extensions — domains where the alphabet really is ASCII and the Unicode rules would be overhead — and a bug when the input is human text.

Because no character can grow or shrink, the result always has the same length and the same character count as the input. That is the property to_lowercase cannot promise.

It still allocates. make_ascii_lowercase does the same transformation in place on a &mut str, and eq_ignore_ascii_case compares without allocating at all.

Example

str_to_ascii_lowercase.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    println!("{:?}", "Hello World".to_ascii_lowercase());

    // Non-ASCII is left exactly as it is.
    let mixed = "CAFÉ Straße";
    println!("{:?}", mixed.to_ascii_lowercase());
    println!("{:?}", mixed.to_lowercase());

    // Length-preserving, which the Unicode version is not.
    for s in ["İ", "ß", "ABC"] {
        println!("{:<5} ascii {} bytes, unicode {} bytes",
                 format!("{s:?}"), s.to_ascii_lowercase().len(), s.to_lowercase().len());
    }

    // Where it is exactly right: an ASCII-by-specification alphabet.
    println!("{:?}", "Content-Type".to_ascii_lowercase());
    println!("{:?}", "IMAGE.PNG".to_ascii_lowercase());
}

Verified output of str_to_ascii_lowercase.rs — regenerated by tools/run_examples.py, never hand-typed.

"hello world"
"cafÉ straße"
"café straße"
"İ"   ascii 2 bytes, unicode 3 bytes
"ß"   ascii 2 bytes, unicode 2 bytes
"ABC" ascii 3 bytes, unicode 3 bytes
"content-type"
"image.png"

See also

str::to_ascii_lowercase in the standard library ↗

Po polsku

Ta strona ma dla polskiego czytelnika ostrzejszą wymowę niż dla angielskiego: to_ascii_lowercase rusza wyłącznie 26 liter AZ, więc "GDAŃSK".to_ascii_lowercase() daje "gdaŃsk" — jedno wielkie Ń uwięzłe w środku małego słowa, a "ŁÓDŹ" wychodzi jako "ŁÓdŹ". Na tekście pisanym przez człowieka jest to po prostu błąd, ale metoda jest dokładnie tym, czego trzeba tam, gdzie alfabet z definicji jest ASCII — nagłówki HTTP, identyfikatory, rozszerzenia plików ("Content-Type""content-type"). W zamian dostaje się gwarancję, której to_lowercase dać nie może: żaden bajt nie przybywa ani nie ubywa, więc długość i liczba znaków zostają nietknięte — porównaj "İ", które w wersji ASCII ma 2 bajty, a po unikodowym to_lowercase już 3.

Szukaj po polsku: polskie znaki diakrytyczne w ASCII · zmiana wielkości liter · rust to_ascii_lowercase vs to_lowercase · rust ascii case insensitive compare