OneBite.Dev - Coding blog in a bite size

Replace Multiple Words In A String In Rust

Code snippet for how to Replace Multiple Words In A String In Rust with sample and detail explanation

In Rust, string handling is integral for many applications and being able to replace multiple words from a string is a valuable technique to add to your skillset. This article will provide you with step-by-step instructions and explanation on how to accomplish this task in Rust.

Code snippet for multi-word string replacement in Rust

fn main() {
    let s = "Hello world, let's write Rust".to_string();
    
    let map = [("Hello", "Hi"), ("world", "Universe"), ("let's", "We will"), ("write", "work with")];

    let new_str: String = map.iter().fold(s, |acc, (a, b)| acc.replace(a, b));

    println!("{}", new_str);
}

Code Explanation for multi-word string replacement in Rust

The main function is the primary function where our code resides and execution begins.

let s = "Hello world, let's write Rust".to_string();

Here, we create a string s that we’ll use for the word replacement.

let map = [("Hello", "Hi"), ("world", "Universe"), ("let's", "We will"), ("write", "work with")];

We define a tuple map with the words we want to replace and what we want to replace them with. The first item in each tuple pair is the word we want to remove, and the second item is the word we want to insert instead.

let new_str: String = map.iter().fold(s, |acc, (a, b)| acc.replace(a, b));

The core of the word replacement functionality is here. We use fold, which is a method that applies a binary operation (in this case, our word replacement) to a sequence of values and accumulates the results. We iterate over our tuple map, and for each tuple pair, we call replace(a, b), replacing word a with word b in our string.

Finally, we print out our new string with the replaced words.

println!("{}", new_str);

That’s it! Now you can replace any number of words in your strings effectively. You just need to update map with the appropriate values. Happy coding in Rust!

rust