I am trying to write a replace_first()
function but I could not find the correct way to manage this.
I have the following input:
let input = "Life is Life".to_string();
I want to replace such input to following romantic output:
My wife is Life
The replace
function replaces all the occurrences. How can I implement the replace_first
function so I can use it like following:
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"
Use 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);
Rust Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With