为什么迭代字符串切片是不可能的?
fn main() {
let text = "abcd";
for (i, c) in text.iter().enumerate() {
// ...
}
}
给出错误error[E0599]: no method named `iter` found for reference `&str` in the current scope
--> src/main.rs:3:24
|
3 | for (i, c) in text.iter().enumerate() {
| ^^^^ method not found in `&str`
如何使字符串切片可迭代?
最佳答案
没有.iter()
为 str
定义的方法;也许是因为它可能是模棱两可的。即使在您的问题中,也不清楚您究竟想要迭代什么,字符或字节。
.bytes()
将产生原始的 utf-8 编码字节 .chars()
将产生 char
s,它们是 unicode 标量值 .graphemes()
来自 unicode-segmentation
crate 为每个“用户感知的字符”生成子字符串 每个都有很多用例,只需选择最合适的。 Playground
use unicode_segmentation::UnicodeSegmentation; // 1.8.0
fn main() {
let text = "🤦🏼♂️"; // browser rendering may vary
println!("{}", text.bytes().count()); // 17
println!("{}", text.chars().count()); // 5
println!("{}", text.graphemes(true).count()); // 1
}
关于rust - 为什么我不能 `.iter()` 字符串切片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69504404/