Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to remove a specificed phrase from a string?

So if I have a string: let foo = "test/string/plz", and I wanted to remove "string", what would be the best way to do so? I have devised a solution below:

fn delete_phrase(input: String, find: String) -> String{
    let mut temp = input.clone();
    
    if input.contains(&find){
        let index = input.find(&find);
        for _i in 0..find.len(){
            temp.remove(index.unwrap());
        }
    }

    return temp.to_string();
}

Is there a better way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can use if let to greatly reduce the code to just an if-else statement:

fn delete_phrase(input: String, find: String) -> String {
    if let Some(index) = input.find(&find) {
        let left = &input[0..index];
        let right = &input[index + find.len()..];
        
        return [left, right].concat();
    } else {
        return input;
    }
}

Then, we’re taking @FilipeRodrigues’s suggestion and using slices to get everything before and after the match. After that, we just need to join the slices together.

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading