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_stringand assigns it the value "Hello World!".let new_string = my_string.replace("World", "Rust");: This line calls thereplacemethod on themy_stringvariable, 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 perform matrix operations in Rust?
- How to make regex case insensitive in Rust?
- How to add an entry to a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
- How to access a mutable index in a Rust HashMap?
- How to modify an existing entry in a Rust HashMap?
- How to convert a slice of bytes to a string in Rust?
- How to convert a vector to a Rust slice?
- How to map a Rust slice?
- How to convert a u8 slice to a hex string in Rust?
See more codes...