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.
for c in "aΓ±b".chars() { print!("{c} "); }
Try it
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.
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
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
charis 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 severalchars. The standard library has no grapheme segmentation; use theunicode-segmentationcrate when you need it. - No indexing by position.
s[3]does not compile. Uses.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_indiceswhen 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 likeb'a'. rev()works onchars()and reverses scalar values, which can detach combining marks from their base letter. It is fine for ASCII and simple text.- Collect into a
Stringwithcollect::<String>()from an iterator ofchar,&strorString. - Use
peekable()for tokenizers that need one character of lookahead.