faker1
V2EX  ›  问与答

rust for loop

  •  
  •   faker1 · Nov 4, 2020 · 2232 views
    This topic created in 2193 days ago, the information mentioned may be changed or developed.

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

    name="hello world"
    for (i:=name.len();i>0;i++){
        // rust 中没有这种比较简单的写法, 只能 loop ?
    }
    
    loop{
        // DOOOOOOOO
    }
    
    
    3 replies  •  2020-11-05 03:31:15 +08:00
    BigDataIsDead
    BigDataIsDead
    Nov 5, 2020
    1
    let mut a = String::from("food");
    for i in 0..a.len() {
    print!("{} ", a.as_bytes()[i] as char);
    }
    BigDataIsDead
    BigDataIsDead
    Nov 5, 2020
    2
    优雅的写法
    ```rust
    for i in a.chars() {
    print!("{} ", i );
    }
    ```
    lostpg
    lostpg
    Nov 5, 2020
    3
    只是字幕数字的话用 as_bytes,遍历 unicode code points 的话,chars() 和 char_indices() 方法。如果有的字符是多个 code points 组成的话,用 https://crates.io/crates/unicode-segmentation 这个 crate 。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2106 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 02:44 · PVG 10:44 · LAX 18:44 · JFK 21:44
    ♥ Do have faith in what you're doing.