获取路径“差异”两个目录之间
情况:
我有一个或多个绝对路径,例如:
- /home/benjamin/test/
- /home/benjamin/test/a/1
- /home/benjamin/test/b/1
我该怎么办得到两条路径之间的差异?假设我想知道如何从路径 1 到达路径 2。预期结果是
/home/benjamin/test/a/1 - /home/benjamin/test/ = /a/1
有没有更优雅的方法而不是将字符串彼此相减?
The situation:
I got one or more absolute paths, e.g.:
- /home/benjamin/test/
- /home/benjamin/test/a/1
- /home/benjamin/test/b/1
How can I get the difference between two paths? Let's say I want to know how I can get from path 1 to path 2. Expected result would be
/home/benjamin/test/a/1 - /home/benjamin/test/ = /a/1
Is there a more elegant way than subtracting the strings from each other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我会尝试使用
std::mismatch
(文档 )将
[first1,last1)
范围内的元素与从first2
开始的范围内的元素按顺序进行比较,并返回第一次不匹配发生的位置。一些代码:
带输出的完整示例已在键盘上上传。
I would try to use
std::mismatch
(documentation)Compares the elements in the range
[first1,last1)
against those in the range beginning atfirst2
sequentially, and returns where the first mismatch happens.Some code:
A full example with output is uploaded at codepad.
我不知道调用 xxxx(...) 的方式,但由于文件路径是树,我会想到 树遍历算法将尽可能优雅......
这个问题。
I don't know a call xxxx(...) way but since the file paths are trees, I would have thought a tree traversal algorithm would be as elegant as it gets...
There is stuff here in this question.
您可以使用简单的正则表达式来完成此操作:
这是Ruby 中的完整示例。您可以在命令行中测试它并开始使用它,或者此代码可以让您了解如何在 C++ 中编写正则表达式。
You can do it with a simple regular expression:
Here is a complete example in Ruby. You can test it out in command-line and start using it or this code can give you an idea how to write the regexp in C++.
您可以将所有路径插入 Trie 中,然后查看保留的后缀。
更一般的做法是使用编辑距离,并回溯最小编辑距离的步骤。
两者对我来说都显得更优雅。然而,首先减去字符串有什么问题呢?
You can insert all paths into a Trie, and see what suffixes remain.
A bit more general is using an edit distance, and retracing the steps for the minimal edit distance.
Both seem more elegant to me. However, what's wrong with subtracting the strings in the first place?
假设您不担心
/home/benjamin/test/c/..
之类的事情,那么这将成为一个简单的子字符串匹配练习。最懒的方法是使用类似
std::string::find< /代码>
。或者,使用一个 while 循环迭代两个字符串,直到到达一个字符串的末尾,或者找到字符差异。
Assuming you're not worried about things like
/home/benjamin/test/c/..
, then this becomes a simple substring matching exercise.The laziest way would be to use something like
std::string::find
. Alternatively, a little while loop that iterates over both strings until it reaches the end of one, or finds a character difference.