代码之家  ›  专栏  ›  技术社区  ›  tyrondis

获取两个目录之间的路径“差异”

  •  2
  • tyrondis  · 技术社区  · 15 年前

    我有一条或多条绝对路径,例如:

    1. /首页/本杰明/测试/
    2. /主页/本杰明/测试/a/1
    3. /主页/本杰明/测试/b/1

    我怎样才能得到这两条路的区别呢?假设我想知道如何从路径1到路径2。预期结果将是

    /home/benjamin/test/a/1-/home/benjamin/test/=/a/1

    5 回复  |  直到 15 年前
        1
  •  2
  •   Arun    15 年前

    我会尽量利用 std::mismatch documentation )

    template <class InputIterator1, class InputIterator2>
      pair<InputIterator1, InputIterator2>
        mismatch (InputIterator1 first1, InputIterator1 last1,
                  InputIterator2 first2 );
    
    Return first position where two ranges differ
    

    比较范围中的元素 [first1,last1) 与那些从 first2 按顺序返回第一个不匹配发生的位置。

    string
    mismatch_string( string const & a, string const & b ) {
    
        string::const_iterator longBegin, longEnd, shortBegin;
    
        if( a.length() >= b.length() ) {
            longBegin = a.begin();
            longEnd = a.end();
            shortBegin = b.begin();
        }
        else {
            longBegin = b.begin();
            longEnd = b.end();
            shortBegin = a.begin();
        }
    
        pair< string::const_iterator, string::const_iterator > mismatch_pair = 
            mismatch( longBegin, longEnd, shortBegin );
    
        return string(  mismatch_pair.first, longEnd );
    }
    

    一个 full example with outpu

        2
  •  1
  •   Community Mohan Dere    9 年前

    我不知道调用xxxx(…)的方式,但是由于文件路径是树,我会想 tree traversal algorithm 会尽可能的优雅。。。

    this question .

        3
  •  1
  •   Aleksandr Levchuk Wes    15 年前

    return($1) if longer =~ /^#{shorter}(.*)$/
    

    这是一个 complete example in Ruby

        4
  •  0
  •   Yuval F    15 年前

    您可以将所有路径插入 Trie ,看看还有什么后缀。

    edit distance ,并按最小编辑距离的步骤进行。

    在我看来两者都更优雅。但是,首先减去字符串有什么问题?

        5
  •  0
  •   Oliver Charlesworth    15 年前

    假设你不担心 /home/benjamin/test/c/.. ,然后这将成为一个简单的子字符串匹配练习。

    std::string::find . 或者,一个小while循环,它在两个字符串上迭代,直到到达一个字符串的末尾,或者找到一个字符差异。