Skip to content
Tutorials Center
My learning

Topics

Rust Reference Β· Strings and Text

Rust str::chars, char_indices and bytes

Reference for Rust str::chars, char_indices and bytes: iterating over Unicode scalar values, byte offsets, counting characters and reversing text.

A Rust string is UTF-8 text, so it has no cheap "n-th character". Instead you pick how to look at it. chars() yields each Unicode scalar value as a char. char_indices() yields the same characters together with the byte offset where each starts. bytes() yields the raw u8 values.

All three are lazy, double-ended iterators, so .rev(), .count(), .enumerate(), .filter() and .collect() all work. They never allocate.

Rust
for c in "aΓ±b".chars() {
    print!("{c} ");
}

Try it

Rust Three ways to walk a string

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Common character tasks

Press Run (or Ctrl + Enter) to see the result here.

Program input Β· what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

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

Returns: Chars yields char; CharIndices yields (usize, char); Bytes yields u8. Chars also has as_str() to get the remaining text, and CharIndices has offset() for the byte offset of the next character.

Errors / panics / edge cases: none panic. Only bytes() knows its length in advance; chars().count() has to scan the whole string because characters have different widths. An empty string gives an empty iterator.

Usage notes

  • A char is a Unicode scalar value, 4 bytes in memory, not a byte and not necessarily what a reader calls a character. Combining marks, emoji with modifiers and flags are several chars. The standard library has no grapheme segmentation; use the unicode-segmentation crate when you need it.
  • No indexing by position. s[3] does not compile. Use s.chars().nth(3) (linear time) or iterate once and keep what you need.
  • len() counts bytes, chars().count() counts scalar values. They differ for any non-ASCII text.
  • Use char_indices when you need offsets to slice with &s[a..b], because offsets from it are always valid boundaries.
  • Use bytes() for ASCII-only or binary-like protocols. It is the fastest, and you can compare with byte literals like b'a'.
  • rev() works on chars() and reverses scalar values, which can detach combining marks from their base letter. It is fine for ASCII and simple text.
  • Collect into a String with collect::<String>() from an iterator of char, &str or String.
  • Use peekable() for tokenizers that need one character of lookahead.