To replace all occurrences of a substring in a string in Rust, you can use the replace
method.
In this example,
str
.replace
method on str
with the substring to be replaced and the replacement string as arguments.replace
method returns a new string with all occurrences of the substring replaced.fn main() {
let mut str = String::from("Hello World Hello");
str = str.replace("Hello", "Hi");
println!("{}", str);
}
Hi World Hi
In this example,
str
.chars_mut
method to obtain a mutable iterator over the characters of the string, then iterate over each character and replace 'o' with 'X'.fn main() {
let mut str = String::from("Hello World Hello");
for c in str.chars_mut() {
if c == 'o' {
*c = 'X';
}
}
println!("{}", str);
}
HellX WXrld HellX
In this tutorial, we learned How to Replace All Occurrences of a Substring in a String in Rust language with well detailed examples.