remove a substring from a string in rust

To remove a substring from a string in Rust, one approach is to use the replace() method of the String type.

main.rs
let my_string = String::from("hello, world");
let substring_to_remove = "world";
let result_string = my_string.replace(substring_to_remove, "");
println!("{}", result_string); // Output: "hello, "
197 chars
5 lines

In the code above, the replace() method replaces all occurrences of the substring_to_remove with an empty string, effectively removing those substrings from the original string.

Alternatively, if you want to remove a specific substring at a given index, you can use Rust's slicing syntax, which allows you to extract a portion of a string as a new string.

main.rs
let my_string = String::from("hello, world");
let start_index = 7;
let end_index = 12;
let result_string = format!("{}{}", &my_string[..start_index], &my_string[end_index..]);
println!("{}", result_string); // Output: "hello, "
228 chars
6 lines

In the code above, we use the slicing syntax &my_string[..start_index] to extract the portion of the string before the start index, and &my_string[end_index..] to extract the portion of the string after the end index. We then use the format!() macro to concatenate the two substrings, effectively removing the substring between them.

gistlibby LogSnag