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?
>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.