如何在 Rust 中惯用地替换特定字符? [英] How do I replace specific characters idiomatically in Rust?
本文介绍了如何在 Rust 中惯用地替换特定字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有字符串Hello World!"并想替换!"和 "?"以便新字符串是Hello World?"
So I have the string "Hello World!" and want to replace the "!" with "?" so that the new string is "Hello World?"
在 Ruby 中,我们可以使用 gsub
方法轻松做到这一点:
In Ruby we can do this easily with the gsub
method:
"Hello World!".gsub("!", "?")
如何在 Rust 中惯用地做到这一点?
How to do this idiomatically in Rust?
推荐答案
你可以用 std::str::replace
:
let result = str::replace("Hello World!", "!", "?");
// Equivalently
result = "Hello World!".replace("!", "?");
println!("{}", result); // => "Hello World?"
对于更复杂的情况,您可以使用regex::Regex::replace_all
来自 regex:
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!"
这篇关于如何在 Rust 中惯用地替换特定字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文