How to Iterate Over a String by Character in Rust
Created
Modified
Using chars Method
The chars()
method returns an iterator over the chars of a string slice. See the following example:
fn main() {
let s = "abc";
for c in s.chars() {
println!("{}", c);
}
// enumerate
for (i, c) in s.chars().enumerate() {
println!("{} {}", i, c);
}
}
a b c 0 a 1 b 2 c
Using Vec
You could also create a vector of chars and work on it from there, but that's more time and space intensive:
fn main() {
let s = "abc";
let v: Vec<_> = s.chars().collect();
println!("{:?}", v);
}
['a', 'b', 'c']
It’s important to remember that char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want.
Using unicode-segmentation
Installation
This crate is fully compatible with Cargo. Just add it to your Cargo.toml:
[dependencies]
unicode-segmentation = "1"
unicode-segmentation Usage
use unicode_segmentation::UnicodeSegmentation;
fn main() {
let s = "a̐";
// chars
for c in s.chars() {
println!("{:?}", c);
}
// UnicodeSegmentation
for g in s.graphemes(true) {
println!("{:?}", g);
}
}
'a' '\u{310}' "a\u{310}"
Rust Compile Errors
no method named `graphemes` found for reference `&str` in the current scope :
// use unicode_segmentation::UnicodeSegmentation;
for g in s.graphemes(true) {
error[E0599]: no method named `graphemes` found for reference `&str` in the current scope --> src/main.rs:5:14 | 5 | for g in s.graphemes(true) { | ^^^^^^^^^ method not found in `&str`