Reputation:
I need to remove all words on one side of a word in a string. I did try str::strip_suffix
, but it didn't do anything.
Here's an example of what I need:
"Hello world, this is a sentence."
(Remove all words from the word "this" and beyond)
"Hello world, "
Upvotes: 2
Views: 2471
Reputation: 523
You can use the function String::replace_range
.
fn main() {
let mut s = String::from("Hello world, this is a sentence.");
let offset = s.find("this").unwrap_or(s.len());
s.replace_range(offset.., "");
println!("{}", s);
}
Upvotes: 1
Reputation: 2561
Without using String
methods, you can also slice on the index returned by find
:
fn main() {
let a = "Hello world, this is a sentence.";
let b = &a[0..a.find("this").unwrap_or(a.len())];
println!("{b}");
}
Upvotes: 3
Reputation: 3360
How about:
fn main() {
let mut msg = "Hello world, this is a sentence.";
if let Some((m, _)) = msg.split_once("this") {
msg = m;
}
println!("{msg:?}");
}
Upvotes: 2