我正在尝试编写一个 replace_first()
函数,但我找不到管理它的正确方法。
我有以下输入:
let input = "Life is Life".to_string();
我想将此类输入替换为以下浪漫输出:
My wife is Life
replace
函数替换所有出现的地方。我如何实现 replace_first
函数,以便我可以像下面这样使用它:
let input = "Life is Life".to_string();
let output = input.replace_first("Life", "My wife");
println!({}, output); // Expecting the output as "My wife is life"
最佳答案
使用replacen
Replaces first N matches of a pattern with another string.
replacen creates a new String, and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice at most count times.
let input = "Life is Life".to_string();
let output = input.replacen("Life", "My wife", 1);
assert_eq!("My wife is Life", output);
关于string - 替换字符串中第一次出现的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54419435/