V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
faker1
V2EX  ›  问与答

rust for loop

  •  
  •   faker1 · Nov 4, 2020 · 1800 views
    This topic created in 2009 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
        1
    BigDataIsDead  
       Nov 5, 2020
    let mut a = String::from("food");
    for i in 0..a.len() {
    print!("{} ", a.as_bytes()[i] as char);
    }
    BigDataIsDead
        2
    BigDataIsDead  
       Nov 5, 2020
    优雅的写法
    ```rust
    for i in a.chars() {
    print!("{} ", i );
    }
    ```
    lostpg
        3
    lostpg  
       Nov 5, 2020
    只是字幕数字的话用 as_bytes,遍历 unicode code points 的话,chars() 和 char_indices() 方法。如果有的字符是多个 code points 组成的话,用 https://crates.io/crates/unicode-segmentation 这个 crate 。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1037 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 18:43 · PVG 02:43 · LAX 11:43 · JFK 14:43
    ♥ Do have faith in what you're doing.