user18608047
user18608047

Reputation:

How to remove everything from a substring on in Rust

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

Answers (3)

Zagatho
Zagatho

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

Jeremy Meadows
Jeremy Meadows

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

hkBst
hkBst

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

Related Questions