Convert path.file_stem() to String

Hi, how to transform Path to String ? or store result in var String ?.
A example please.
This is good ?: path.file_stem().expect("REASON").to_str().unwrap()
Thanks

use std::path::Path;

let path = Path::new("/home/pichi/bar.txt");
let name_file = String::from(&path.file_stem());

println!("The Name is: { }", &name_str);
1 Like

Yup, that should do the trick!

1 Like

Another questions:

let mut s1 = String::from("Jesus Cristo [2016] - 087.mp4");
let n_vector = vec!["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

let s1 = s1.replace("-", ""); // this Work! Fine
for r in &n_vector {  // it does not work :(
    s1.replace(r, "");
}

You should have received a compiler warning about the one that does not work. replace allocates a new string, it doesn't mutate it in-place. This is clearly described in its documentation.

If you take a look at the function definition of replace() you know why:

pub fn replace<'a, P>(&'a self, from: P, to: &str) -> String where P: Pattern<'a>

The function is implemented on a string slice &str (and not String) and returns a new String, because the the result string could grow in size. For example, if you replace "a" in let src = "abc" with "ä" (let dest = "äbc"), the length of the src would be 3, but the length of dest would be 4.

Your fixed code would look like this:

let mut s1 = String::from("Jesus Cristo [2016] - 087.mp4");
let n_vector = vec!["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

let s1 = s1.replace("-", ""); // this Work! Fine
for r in &n_vector {  // it does not work :(
    s1 = s1.replace(r, "");
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.