如何在 Rust 中惯用地替换特定字符?

2024-03-13

所以我有字符串“Hello World!”并想替换“!”和 ”?”这样新字符串就是“Hello World?”

在 Ruby 中,我们可以使用以下命令轻松完成此操作gsub method:

"Hello World!".gsub("!", "?")

如何在 Rust 中惯用地做到这一点?


您可以将一个字符串在另一个字符串中出现的所有位置替换为str::replace https://doc.rust-lang.org/std/primitive.str.html#method.replace:

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

对于更复杂的情况,您可以使用regex::Regex::replace_all https://docs.rs/regex/1.3.3/regex/struct.Regex.html#method.replace_all from regex https://docs.rs/regex/1.3.3/regex/index.html:

use regex::Regex;
let re = Regex::new(r"[A-Za-z]").unwrap();
let result = re.replace_all("Hello World!", "x");
println!("{}", result); // => "xxxxx xxxxx!"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Rust 中惯用地替换特定字符? 的相关文章

随机推荐