To remove a specific substring from a string in Rust, you can use the `str::replace` method.
In this example,
mut str
with a value of "Hello World"
.replace
method of the string object str
to replace the substring "World"
with an empty string ""
.replace
method returns a new string with the specified substring replaced.str
to the console.fn main() {
let mut str = String::from("Hello World");
str = str.replace("World", "");
println!("Modified string: {}", str);
}
Modified string: Hello
In this example,
mut text
with a value of "I like apple pie"
.replace
method of the string object text
to replace the substring "apple"
with an empty string ""
.replace
method creates and returns a new string with all occurrences of the specified substring replaced.text
to the console.fn main() {
let mut text = String::from("I like apple pie");
text = text.replace("apple", "");
println!("Modified string: {}", text);
}
Modified string: I like pie
In this tutorial, we learned How to Remove specific Substring in Rust language with well detailed examples.