rustHow do I replace a string in Rust?
Replacing a string in Rust is a simple task that can be accomplished using the replace
method. This method takes two parameters, the first being the string to be replaced and the second being the string to replace it with.
Example
let my_string = "Hello World!";
let new_string = my_string.replace("World", "Rust");
println!("{}", new_string);
Output example
Hello Rust!
The code above replaces the string "World" with "Rust" in the variable my_string
. The replace
method returns a new string with the replaced value.
Code explanation
let my_string = "Hello World!";
: This line declares a variablemy_string
and assigns it the value "Hello World!".let new_string = my_string.replace("World", "Rust");
: This line calls thereplace
method on themy_string
variable, replacing the string "World" with "Rust".println!("{}", new_string);
: This line prints the new string with the replaced value to the console.
Helpful links
More of Rust
- How to use regex to match a group in Rust?
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to match the end of a line in a Rust regex?
- How to get a capture group using Rust regex?
- How to create a new Rust HashMap with values?
- How to use regex with bytes in Rust?
- How to get an entry from a HashSet in Rust?
- How to create a HashMap of HashMaps in Rust?
See more codes...