How do I replace specific characters idiomatically in Rust?

前端 未结 2 1404
既然无缘
既然无缘 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 01:18

    Also you can use iterators and match expression:

    let s:String = "Hello, world!".chars()
        .map(|x| match x { 
            '!' => '?', 
            'A'..='Z' => 'X', 
            'a'..='z' => 'x',
            _ => x
        }).collect();
    println!("{}", s);// Xxxxx, xxxxx?
    

提交回复
热议问题