Rust 1.99 (2024 edition) reference · Strings

Rust str::chars and char_indices Method

Iterate over the Unicode characters of a string (not bytes), with their byte positions when needed.

Rust 1.99 (2024 edition)

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

fn chars(&self) -> Chars<'_>   fn char_indices(&self) -> CharIndices<'_>   fn bytes(&self) -> Bytes<'_>

Parameters

ParameterDescription
chars() Unicode scalar values.
char_indices() (byte offset, char) pairs.
bytes() Raw UTF-8 bytes.

Examples

Example 1
fn main() {
    let word = "naïve";
    println!("{} bytes, {} chars", word.len(), word.chars().count());
    let reversed: String = word.chars().rev().collect();
    println!("{reversed}");
    for (i, c) in word.char_indices().filter(|(_, c)| !c.is_ascii()) {
        println!("non-ASCII {c} at byte {i}");
    }
}

Output

6 bytes, 5 chars
evïan
non-ASCII ï at byte 2

Run this on your computer — see “Get Started” for setup.

Classifying characters
fn main() {
    let code = "A1b2";
    let digits: u32 = code.chars().filter_map(|c| c.to_digit(10)).sum();
    let upper = code.chars().filter(|c| c.is_uppercase()).count();
    println!("digit sum {digits}, uppercase {upper}");
}

Output

digit sum 3, uppercase 1

Run this on your computer — see “Get Started” for setup.

Was this page helpful?