How do I replace specific characters idiomatically in Rust?

前端 未结 2 1403
既然无缘
既然无缘 2021-02-05 00:45

So I have the string \"Hello World!\" and want to replace the \"!\" with \"?\" so that the new string is \"Hello World?\"

In Ruby we can do this easily with the gs

2条回答
  •  鱼传尺愫
    2021-02-05 00:59

    You can replace all occurrences of one string within another with std::str::replace:

    let result = str::replace("Hello World!", "!", "?");
    // Equivalently
    result = "Hello World!".replace("!", "?");
    println!("{}", result); // => "Hello World?"
    

    For more complex cases, you can use regex::Regex::replace_all from regex:

    use regex::Regex;
    let re = Regex::new(r"[A-Za-z]").unwrap();
    let result = re.replace_all("Hello World!", "x");
    println!("{}", result); // => "xxxxx xxxxx!"
    

提交回复
热议问题