作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有兴趣这样做的原因是因为我的路径中有一部分将保持不变,但我希望将其与其所有父部分一起删除。
所以如果我们说,
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"
(这将分配一个新的 PathBuf
。Shepmaster's answer 展示了如何在不分配的情况下获取引用原始文件的 &Path
。)
然后您可以使用 to_str
, to_string_lossy
, 或 into_os_string
加上 OsString::into_string
得到可以变成 String
的东西。
关于path - 我可以使用 `std::path::Path` 的 `strip_prefix` 来替换动态前缀吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50109230/
我有兴趣这样做的原因是因为我的路径中有一部分将保持不变,但我希望将其与其所有父部分一起删除。 所以如果我们说, some/unknown/path/foo/bar/baz 我想回去 bar/baz 但
我是一名优秀的程序员,十分优秀!