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)
Syntax
fn chars(&self) -> Chars<'_> fn char_indices(&self) -> CharIndices<'_> fn bytes(&self) -> Bytes<'_>
Parameters
| Parameter | Description |
|---|---|
chars() |
Unicode scalar values. |
char_indices() |
(byte offset, char) pairs. |
bytes() |
Raw UTF-8 bytes. |
Examples
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.
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.
Related
String and &str methods· Common text operations: trim, split, contains, replace, case conversion, starts_with and parse.- Rust Slices and Strings · tutorial