gpt4 book ai didi

path - 我可以使用 `std::path::Path` 的 `strip_prefix` 来替换动态前缀吗?

转载 作者:行者123 更新时间:2023-11-29 08:22:45 31 4
gpt4 key购买 nike

我有兴趣这样做的原因是因为我的路径中有一部分将保持不变,但我希望将其与其所有父部分一起删除。

所以如果我们说,

some/unknown/path/foo/bar/baz

我想回去

bar/baz

但我只知道 foo/... 的期望直接继续我关心的路径部分。

也许 strip_prefix 是错误的方法,所以如果有更好的方法来做到这一点,我当然会很感激被指出那个方向。

最佳答案

strip_prefix 不会执行您想要的操作,因为它要求您知道要去除的前缀。但是,您可以使用 iter获取路径组件的迭代器,然后使用标准的 Iterator 方法从您想要的部分构建一个新的 PathBuf

这是一个例子(try it):

let p = path::Path::new("some/unknown/path/foo/bar/baz");
let q: path::PathBuf = p.iter() // iterate over path components
.skip_while(|s| *s != "foo") // skip everything before "foo"
.skip(1) // skip "foo" itself
.collect(); // collect the rest into a PathBuf
println!("{:?}", q); // prints "bar/baz"

(这将分配一个新的 PathBufShepmaster's answer 展示了如何在不分配的情况下获取引用原始文件的 &Path。)

然后您可以使用 to_str , to_string_lossy , 或 into_os_string加上 OsString::into_string得到可以变成 String 的东西。

另请参阅:How to convert the PathBuf to String

关于path - 我可以使用 `std::path::Path` 的 `strip_prefix` 来替换动态前缀吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50109230/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com