V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
faker1
V2EX  ›  问与答

rust for loop

  •  
  •   faker1 · 2020-11-04 23:05:51 +08:00 · 989 次点击
    这是一个创建于 1267 天前的主题,其中的信息可能已经有所发展或是发生改变。

    想遍历一个字符串,半天没有找到能 work 的

    name="hello world"
    for (i:=name.len();i>0;i++){
        // rust 中没有这种比较简单的写法, 只能 loop ?
    }
    
    loop{
        // DOOOOOOOO
    }
    
    
    3 条回复    2020-11-05 03:31:15 +08:00
    Co1a
        1
    Co1a  
       2020-11-05 03:12:31 +08:00
    let mut a = String::from("food");
    for i in 0..a.len() {
    print!("{} ", a.as_bytes()[i] as char);
    }
    Co1a
        2
    Co1a  
       2020-11-05 03:23:14 +08:00
    优雅的写法
    ```rust
    for i in a.chars() {
    print!("{} ", i );
    }
    ```
    lostpg
        3
    lostpg  
       2020-11-05 03:31:15 +08:00
    只是字幕数字的话用 as_bytes,遍历 unicode code points 的话,chars() 和 char_indices() 方法。如果有的字符是多个 code points 组成的话,用 https://crates.io/crates/unicode-segmentation 这个 crate 。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5415 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 08:36 · PVG 16:36 · LAX 01:36 · JFK 04:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.