Is there a method like JavaScript's substr in Rust?

前端 未结 7 1200
天命终不由人
天命终不由人 2021-02-02 10:21

I looked at the Rust docs for String but I can\'t find a way to extract a substring.

Is there a method like JavaScript\'s substr in Rust? If not, how would you implement

7条回答
  •  無奈伤痛
    2021-02-02 11:04

    You can also use .to_string()[ ].

    This example takes an immutable slice of the original string, then mutates that string to demonstrate the original slice is preserved.

    let mut s: String = "Hello, world!".to_string();
    
    let substring: &str = &s.to_string()[..6];
    
    s.replace_range(..6, "Goodbye,");
    
    println!("{}   {} universe!", s, substring);
    
    //    Goodbye, world!   Hello, universe!
    

提交回复
热议问题