Home > database >  Need to extract the last word in a Rust string
Need to extract the last word in a Rust string

Time:12-14

I am doing some processing of a string in Rust, and I need to be able to extract the last set of characters from that string. In other words, given a string like the following:

some|not|necessarily|long|name

I need to be able to get the last part of that string, namely "name" and put it into another String or a &str, in a manner like:

let last = call_some_function("some|not|necessarily|long|name");

so that last becomes equal to "name".

Is there a way to do this? Is there a string function that will allow this to be done easily? If not (after looking at the documentation, I doubt that there is), how would one do this in Rust?

CodePudding user response:

You can use the String::split() method, which will return an iterator over the substrings split by that separator, and then use the Iterator::last() method to return the last element in the iterator, like so:

let s = String::from("some|not|necessarily|long|name");
let last = s.split('|').last().unwrap();
    
assert_eq!(last, "name");

Please also note that string slices (&str) also implement the split method, so you don't need to use std::String.

let s = "some|not|necessarily|long|name";
let last = s.split('|').last().unwrap();
    
assert_eq!(last, "name");
  • Related