【问题标题】:Why can I not `.iter()` a string slice?为什么我不能`.iter()` 一个字符串切片?
【发布时间】:2021-11-28 22:01:08
【问题描述】:

为什么不能遍历字符串切片?

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`

如何使字符串切片可迭代?

【问题讨论】:

标签: rust


【解决方案1】:

要迭代字符串字符,可以使用chars() 方法:

fn main() {
    let text = "abcd";
    for (i, c) in text.chars().enumerate() {
       println!("i={} c={}", i, c) 
    } 
}

【讨论】:

    【解决方案2】:

    没有为str 定义.iter() 方法;也许是因为它可能是模棱两可的。即使在您的问题中,也不清楚您究竟想要迭代什么,charactersbytes

    • .bytes() 将产生原始的 utf-8 编码字节
    • .chars() 将产生 chars,它们是 unicode 标量值
    • 或者可能来自unicode-segmentation crate 中的.graphemes(),它为每个“用户感知字符”生成子字符串

    每种都有很多用例,只需选择最合适的用例即可。 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
    }
    

    【讨论】:

      猜你喜欢
      • 2011-09-13
      • 2022-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 2018-10-18
      • 2022-08-18
      相关资源
      最近更新 更多